http://www.perlmonks.org?node_id=407212


in reply to To & or not to & ?

$result = function(@args) would be usual syntax. You almost never need &. The main effects of & are that it passes @_ to the called function and you don't need () after the function name to pass strict. However do note that &::function and ::function are calling main::function(). This matters if you are in another package:

#package main; # this is implicit bar( qw( some args that were passed along ) ); foo( 'foo() stuff' ); ::foo( '::foo() stuff' ); &::foo( '&::foo() stuff' ); sub bar { &foo; } sub foo { print __PACKAGE__, " foo got '@_'\n" } foo; # bareword will work with no strictures after sub defn package Foo; foo( 'foo() stuff' ); ::foo( '::foo() stuff' ); &::foo( '&::foo() stuff' ); sub foo { print __PACKAGE__, " foo got '@_'\n" } __DATA__ main foo got 'some args that were passed along' main foo got 'foo() stuff' main foo got '::foo() stuff' main foo got '&::foo() stuff' main foo got '' Foo foo got 'foo() stuff' main foo got '::foo() stuff' main foo got '&::foo() stuff'

cheers

tachyon

Replies are listed 'Best First'.
Re^2: To & or not to & ?
by Aighearach on Nov 11, 2004 at 23:29 UTC
    Note that, & only passes @_ IF you leave off the parens.

    So that, if bar was implemented

    sub bar { &foo(); }
    then it wouldn't pass anything at all to foo. So, &FUNC should be considered a different way to call than &FUNC(), because only one of them does something different than FUNC()

    --
    Snazzy tagline here
      because only one of them does something different than FUNC()

      Actually, all of them do something different as shown below:

      > perl -le'@_=2;sub a($$) {shift or 1};print &a' 2 > perl -le'@_=2;sub a($$) {shift or 1};print &a()' 1 > perl -le'@_=2;sub a($$) {shift or 1};print a()' Not enough arguments for main::a at -e line 1, at end of line Execution of -e aborted due to compilation errors.

      Sorry for the pedantry.

      A reply falls below the community's threshold of quality. You may see it by logging in.