password636 password636 - 1 year ago 57
Perl Question

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

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

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 line 16, near "&aname "arg1""
(Missing operator before "arg1"?)
syntax error at line 16, near "&aname "arg1""
Execution of 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.


Answer Source

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.