8

for a Perl subroutine, if passing 0 argument, I can use 4 forms to call it. But if passing 1 or more arguments, there is one form that I can't use, please see below:

sub name
{
    print "hello\n";
}
# 4 forms to call
name;
&name;
name();
&name();

sub aname
{
        print "@_\n";
}
aname "arg1", "arg2";
#&aname "arg1", "arg2"; # syntax error
aname("arg1", "arg2");
&aname("arg1", "arg2");

The error output is

String found where operator expected at tmp1.pl line 16, near "&aname "arg1""
    (Missing operator before  "arg1"?)
syntax error at tmp1.pl line 16, near "&aname "arg1""
Execution of tmp1.pl aborted due to compilation errors.

Can someone explain the error output from the compiler's point of view? I don't understand why it complains about missing operator.

Thanks

password636
  • 981
  • 1
  • 7
  • 18
  • 3
    You got a great answer. For a lot more discussion about the use of `&` for this see [`this post`](http://stackoverflow.com/questions/1347396/when-should-i-use-the-to-call-a-perl-subroutine), and [`this post`](http://stackoverflow.com/questions/8912049/difference-between-function-and-function-in-perl), and [`this post`](http://stackoverflow.com/questions/6706882/using-ampersands-and-parens-when-calling-a-perl-sub) ... and there are probably others. – zdim Sep 21 '16 at 07:48
  • 1
    @zdim just wondering, why did you put the links in code markup? – simbabque Sep 21 '16 at 08:29
  • @simbabque Hah, good point. I suppose so that they are more visible, highlighted. Don't really know. Never really thought about it as "code markup" (you are right, it is) -- but more as of highlight. – zdim Sep 21 '16 at 08:34

1 Answers1

13

It's documented in perlsub:

To call subroutines:

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

With &NAME "arg", perl sees &NAME() "ARG", so it thinks there's an operator missing between the sub call and "ARG".

In Perl 5, you don't need the & in most cases.

choroba
  • 231,213
  • 25
  • 204
  • 289