Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using ampersands and parens when calling a Perl sub

Tags:

perl

#!/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.

like image 260
Je Rog Avatar asked Jul 15 '11 12:07

Je Rog


1 Answers

Calling a subroutine using the &NAME; syntax makes current @_ visible to it. This is documented in perlsub:

If a subroutine is called using the & form, the argument list is optional, and if omitted, no @_ array is set up for the subroutine: the @_ array at the time of the call is visible to subroutine instead. This is an efficiency mechanism that new users may wish to avoid.

So, it's definitely a feature.

like image 116
Eugene Yarmash Avatar answered Oct 07 '22 12:10

Eugene Yarmash