Alex Rivera | Logout

Using ampersands and parens when calling a Perl sub

Asked 2011-07-15T12:22:28.480
14
#!/usr/bin/perl

sub t {
  print "in t\n";
  print "@_\n";
  &s;
}

sub s {
  print "in s\n";
  print "@_\n";
}

t(1,2);
print "out\n";
print "@_\n";

Output:

in t
1 2
in s
1 2
out

As you see,&s output 1 2 when no parameter is passed. Is this a feature or a bug?

Tested version is 5.8.8.

Edit
Report

1 Answer

18

When using & before the sub name and no argument list is passed, the current @_ is passed as argument instead. So, it is a feature.

Here are the different ways to call a subroutine:

NAME(LIST); # & is optional with parentheses.
NAME LIST;  # Parentheses optional if predeclared/imported.
&NAME(LIST); # Circumvent prototypes.
&NAME;      # Makes current @_ visible to called subroutine.

from perldoc perlsub

answered 2011-07-15T12:32:04.203

Your Answer