【问题标题】:why the syntax `&name arg1 arg2 ...` can't be used to call a Perl subroutine?为什么语法 `&name arg1 arg2 ...` 不能用于调用 Perl 子例程?
【发布时间】:2017-01-29 07:58:59
【问题描述】:

对于 Perl 子程序,如果传递 0 参数,我可以使用 4 种形式来调用它。但如果传递 1 个或多个参数,则有一种形式无法使用,请参见下文:

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");

错误输出是

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.

有人可以从编译器的角度解释错误输出吗?我不明白为什么它抱怨缺少操作员。

谢谢

【问题讨论】:

  • 你得到了一个很好的答案。有关使用& 的更多讨论,请参阅this postthis postthis post ...可能还有其他人。
  • @zdim 只是想知道,你为什么将链接放在代码标记中?
  • @simbabque 哈哈,好点子。我想这样它们会更明显、更突出。真不知道。从来没有真正将其视为“代码标记”(你说得对,它是)——但更多的是高亮。

标签: perl syntax subroutine invocation


【解决方案1】:

记录在perlsub:

调用子程序:

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

使用&NAME "arg",perl 看到&NAME() "ARG",所以它认为在子调用和“ARG”之间缺少一个运算符。

在 Perl 5 中,大多数情况下您不需要 &

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多