Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
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

like image 248
password636 Avatar asked Sep 21 '16 07:09

password636


People also ask

Why is the syntax important?

"Syntax skills help us understand how sentences work—the meanings behind word order, structure, and punctuation. By providing support for developing syntax skills, we can help readers understand increasingly complex texts" (Learner Variability Project).

What do you mean syntax?

Syntax is the grammar, structure, or order of the elements in a language statement. (Semantics is the meaning of these elements.) Syntax applies to computer languages as well as to natural languages.

Why is syntax important in speaking?

Among the fundamental linguistic aspects of normal speech is syntax, which governs the order of words arranged into sentences. Syntactic structure is of particular interest in speech-on-speech masking because it bears directly on the issue of predictability.

Why is it called a syntax?

The word 'syntax' is derived from the Greek word 'syntaxis' , meaning 'together' and 'sequence' . The term is used for the way in which words are put together in an orderly system to form phrases or sentences. Basically, syntax is the rule by which signs are combined to make statements.


1 Answers

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.

like image 111
choroba Avatar answered Oct 19 '22 09:10

choroba