www.fgks.org   »   [go: up one dir, main page]

Beefy Boxes and Bandwidth Generously Provided by pair Networks Cowboy Neal with Hat
Perl Monk, Perl Meditation.
 
PerlMonks

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

by tphyahoo
 | Log in | Create a new user | The Monastery Gates | Super Search | 
 | Seekers of Perl Wisdom | Meditations | PerlMonks Discussion | Snippets | 
 | Obfuscation | Reviews | Cool Uses For Perl | Perl News | Q&A | Tutorials | 
 | Code | 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 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 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 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 on Feb 04, 2005 at 15:24 UTC
[reply]
Re: What is the point of the & / ampersand sigil for function refs?
by dimar 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
password reminder
Create A New User

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

How do I use this? | Other CB clients
Other Users
Others exploiting the Monastery: (10)
Joost
jdporter
atcroft
Moriarty
castaway
blue_cowdawg
moklevat
Cristoforo
perlsyntax
mirage_zz
As of 2007-09-27 00:08 GMT
Sections
The Monastery Gates
Seekers of Perl Wisdom
Meditations
PerlMonks Discussion
Categorized Q&A
Tutorials
Obfuscated Code
Perl Poetry
Cool Uses for Perl
Snippets Section
Code Catacombs
Perl News
Information
PerlMonks FAQ
What's New at PerlMonks
Guide to the Monastery
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
Quests
Editor Requests
Buy PerlMonks Gear
PerlMonks Merchandise
Perl Buzz
Perl.com
Perl Directory
Perl documentation
CPAN
Random Node
Voting Booth

You've just spilled something on your tie at lunch... Do you:

Leave the tie on
Take the tie off
Ignore it since your tie is so ugly no one will notice
Ignore it since it makes your tie look better
Accessorize the stain by covering it with a band-aid
Put on the spare tie from the bottom drawer
Go buy a spare tie for the bottom drawer
Improvise a new tie out of office supplies
Ties? We don't need no steenking ties!
I'm personally bringing back the Nehru collar look (since Keanu killed it)
Be thankful that it was only a hard copy of your source code

Results (321 votes), past polls