why the syntax `&name arg1 arg2 ...` can't be used to call a Perl subroutine?
Asked Answered
R

1

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

Rad answered 21/9, 2016 at 7:37 Comment(3)
You got a great answer. For a lot more discussion about the use of & for this see this post, and this post, and this post ... and there are probably others.Kristiankristiansand
@Kristiankristiansand just wondering, why did you put the links in code markup?Accrue
@Accrue 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.Kristiankristiansand
P
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.

Piquant answered 21/9, 2016 at 7:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.