Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

Re: why avoid & on function call -- defending & syntax

by Discipulus (Canon)
on Dec 28, 2020 at 10:55 UTC ( [id://11125859]=note: print w/replies, xml ) Need Help??


in reply to why avoid & on function call

Hello fireblood,

> I've always used a leading ampersand when calling &my_function and have never noticed a problem.

Me too I was used to code this way, even if discouraged many times by other monks. I knew the eventual pitfalls and all differences between the two syntax.

I always used &my_func( 42 ) to highlight that sub was defined in the current file and not coming from an external module ( update: I found this very useful in my first years of programming, when the whole mess of internal functions, local and imported subs was difficult to distinguish at glance ).

Many perl programmers hate this syntax, telling you to avoid it: this is not true. The & is optional

> A subroutine may be called using an explicit & prefix. The & is optional in modern Perl, as are parentheses if the subroutine has been predeclared. The & is not optional when just naming the subroutine, such as when it's used as an argument to defined() or undef(). Nor is it optional when you want to do an indirect subroutine call with a subroutine name or reference using the &$subref() or &{$subref}() constructs, although the $subref->() notation solves that problem.

The above quote from perlsub states it clearly and tell us even more: you must know this syntax because sometimes it must be used.

So, imho, you have not to avoid it but you have to be aware of what it implies and you got good answers about it.

Extending a bit what perlsub says you can have the following:

NAME(LIST); # & is optional with parentheses. NAME LIST; # Parentheses optional if predeclared/imported. &NAME(LIST); # Circumvent prototypes. &NAME; # Makes current @_ visible to called subroutine. defined(&NAME); # & is needed. The same is valid for undef(&NAME) and + any case when you are naming your sub &$subref(); # & is needed. But $subref->() can be used to avoid t +he & &{$subref}(); # & is needed. But $subref->() can be used to avoid t +he &

L*

There are no rules, there are no thumbs..
Reinvent the wheel, then learn The Wheel; may be one day you reinvent one of THE WHEELS.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11125859]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others surveying the Monastery: (3)
As of 2024-04-19 23:52 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found