Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight

Re: What is the point of the & sigil for function refs?

by bpphillips (Friar)
on Feb 04, 2005 at 13:21 UTC ( #428050=note: print w/replies, xml ) Need Help??

in reply to What is the point of the & / ampersand sigil for function refs?

As merlyn eluded to above, you can omit parens when you use a & in front of the function call. This has an interesting "side-effect" in that the local @_ is implicitly passed to that sub even though no arguments are explicitly passed. For instance:
foo("\@_ has elements!"); # prints "Surprise! @_ has elements!" bar("\@_ has no elements!"); # prints "Surprise!" sub foo { # absent parens say pass my @_ &baz; } sub bar { # parens say only pass these arguments (nothing) &baz(); } sub baz { print "Surprise! ",join("\t",@_),"\n"; }
This can be handy when golfing but might cause anyone who looks at your code (including you!) some headaches...


Replies are listed 'Best First'.
Re^2: What is the point of the & sigil for function refs?
by ihb (Deacon) on Feb 11, 2005 at 14:20 UTC

    the local @_ is implicitly passed

    It's even the same @_. This means that &foo(@_) and &foo; won't behave the same; see perlfaq7, "What's the difference between calling a function as &foo and foo()?". Demonstration:

    use strict; sub foo { pop } sub bar { print "bar before: @_"; print '&foo : ' . &foo . " <--- I am a theif"; print "bar after : @_ <--- no c"; } sub baz { print "baz before: @_"; print '&foo(@_) : ' . &foo(@_); print "baz after : @_"; } bar(qw/ a b c /); print ''; baz(qw/ a b c /); __END__ bar before: a b c &foo : c <--- I am a theif bar after : a b <--- no c baz before: a b c &foo(@_) : c baz after : a b c


    See perltoc if you don't know which perldoc to read!

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://428050]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others studying the Monastery: (5)
As of 2018-05-25 20:57 GMT
Find Nodes?
    Voting Booth?