Beefy Boxes and Bandwidth Generously Provided by pair Networks Bob
Just another Perl shrine
 
PerlMonks

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

by tphyahoo (Vicar)
 | Log in | Create a new user | The Monastery Gates | Super Search | 
 | Seekers of Perl Wisdom | Meditations | PerlMonks Discussion | 
 | Obfuscation | Reviews | Cool Uses For Perl | Perl News | Q&A | Tutorials | 
 | Poetry | Recent Threads | Newest Nodes | Donate | What's New | 

on Feb 04, 2005 at 12:02 UTC ( #428024=perlquestion: print w/ replies, xml ) Need Help??
tphyahoo has asked for the wisdom of the Perl Monks concerning the following question:

In the following code, I can call a module function using &, or not using &. Is there ever a scenario when it's preferrable to use the &? Where can I learn more about this?

#!perl #test.pl use strict; use warnings; #custom modules use lib 'E:/data/entwicklungsArena/perl/development/modules'; #Works use Misc::Logger; print 'without &: '; Misc::Logger::logMessage("test"); #Also works: print 'with &: '; &Misc::Logger::logMessage("test");

Comment on What is the point of the & / ampersand sigil for function refs?
Download Code
Re: What is the point of the & sigil for function refs?
by merlyn (Cardinal) on Feb 04, 2005 at 12:14 UTC
    The & prefix unambiguously means "this is a user-defined subroutine call coming up next". You can omit it when you are using parens after your function name and your function name doesn't conflict with a built-in, or if you've declared/defined your function before you use it and the name doesn't conflict with a built-in.

    The & prefix also disables prototype checking, but you shouldn't be using prototypes in the first place, so I consider that a very minor point, but if I didn't mention it, someone else would surely raise that flag. {grin}

    In our Learning Perl book, we suggest that you always use the ampersand when you're first learning Perl, because otherwise you'll be a bit befuddled when the following code doesn't work:

    sub log { print STDERR "logging: ", @_, "\n"; } ... log("starting"); ... log("finishing"); ...
    Yes, you're not calling your log subroutine... you're calling the built-in "logarithm" function. Oops.

    -- Randal L. Schwartz, Perl hacker
    Be sure to read my standard disclaimer if this is a reply.

[reply]
[d/l]

      > The & prefix also disables prototype checking, but you shouldn't be using prototypes in the first place,
      > so I consider that a very minor point, but if I didn't mention it, someone else would surely raise that flag. {grin}

      I was going to ask for clarification here as I thought prototypes were good ju-perl. How mistaken I was, a supersearch lead me to this node Gratuitous use of Perl Prototypes. Another step on the path to enlightenment.

      Thanks,
      R.

      Pereant, qui ante nos nostra dixerunt!
[reply]
Re: What is the point of the & sigil for function refs?
by bpphillips (Friar) on Feb 04, 2005 at 13:21 UTC
    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...

    --Brian
[reply]
[d/l]
[select]

      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

      ihb

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

[reply]
[d/l]
[select]
Re: What is the point of the & sigil for function refs?
by grinder (Bishop) on Feb 04, 2005 at 13:28 UTC
    Is there ever a scenario when it's preferrable to use the &

    There is one dramatic difference that occurs when you call the function without a parameter list:

    #! /usr/local/bin/perl -w use strict; sub inner { print " inner: $_\n" for @_; } sub outer { print "outer: $_\n" for @_; inner; print "\n"; } sub outer_amp { print "outer_amp: $_\n" for @_; &inner; print "\n"; } outer( qw/ vroon gukguk faba / ); outer_amp( qw/ foomp tweedle zachitty / ); __RESULTS__ outer: vroon outer: gukguk outer: faba outer_amp: foomp outer_amp: tweedle outer_amp: zachitty inner: foomp inner: tweedle inner: zachitty

    When using the &inner variant, whatever remains of @_ in the calling routine is passed to the called routine. The only time it's really useful is when doing out-of-the-ordinary stuff like autoloading. In general you should avoid it. It leads to bad surprises

    PS: metasyntactic function call arguments courtesy of BooK's Acme::MetaSyntactic module, the donmartin theme.

    - another intruder with the mooring in the heart of the Perl

[reply]
[d/l]
Re: What is the point of the & sigil for function refs? (oldie)
by tye (Archbishop) on Feb 04, 2005 at 15:24 UTC
[reply]
Re: What is the point of the & / ampersand sigil for function refs?
by dimar (Curate) on Feb 07, 2005 at 17:17 UTC
    Where can I learn more about this?

    A somewhat related inquiry follows at: Subroutine Bewilderment with some helpful comments.

[reply]

Back to Seekers of Perl Wisdom


Login:
Password
remember me
What's my password?
Create A New User

Node Status
node history
Node Type: perlquestion [id://428024]
Approved by skx
Front-paged by Old_Gray_Bear
help
Community Ads
Chatterbox
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users
Others lurking in the Monastery: (10)
planetscape
bassplayer
atcroft
herveus
thezip
Eyck
ssandv
Madams
gnosti
spstansbury
As of 2009-11-21 01:55 GMT
Sections
The Monastery Gates
Seekers of Perl Wisdom
Meditations
PerlMonks Discussion
Categorized Q&A
Tutorials
Obfuscated Code
Perl Poetry
Cool Uses for Perl
Perl News
Information
PerlMonks FAQ
Guide to the Monastery
What's New at PerlMonks
Voting/Experience System
Tutorials
Reviews
Library
Perl FAQs
Other Info Sources
Find Nodes
Nodes You Wrote
Super Search
List Nodes By Users
Newest Nodes
Recently Active Threads
Selected Best Nodes
Best Nodes
Worst Nodes
Saints in our Book
Leftovers
The St. Larry Wall Shrine
Offering Plate
Awards
Craft
Snippets Section
Code Catacombs
Quests
Editor Requests
Buy PerlMonks Gear
PerlMonks Merchandise
Planet Perl
Perlsphere
Use Perl
Perl.com
Perl 5 Wiki
Perl Jobs
Perl Mongers
Perl Directory
Perl documentation
CPAN
Random Node
Voting Booth

Future historians will find that the material characteristic of the current era is...

Aluminium
Plastic
Oil
Water
Carbon dioxide
Copper
Iron
Silicon
Salt
Uranium
Hydrogen
Other

Results (725 votes), past polls