为什么Perl子需要&

Bry*_*eld 3 perl compiler-errors reserved-words subroutine

以下文件无法编译:

sub s {
    return 'foo';
}
sub foo {
    my $s = s();
    return $s if $s;
    return 'baz?';
}
Run Code Online (Sandbox Code Playgroud)

错误来自perl -c:

syntax error at foobar.pl line 5 near "return"
  (Might be a runaway multi-line ;; string starting on line 3)
foobar.pl had compilation errors.
Run Code Online (Sandbox Code Playgroud)

但如果我s()&s()它替换它工作正常.你能解释一下原因吗?

Mik*_*ike 13

&前缀明确表示你要调用自己的名为"s"的函数,而不是任何具有相同名称的内置函数.在这种情况下,它$stuff =~ s///;会使替换运算符混淆(例如,也可以写入s()()).

这是关于&符号的PerlMonks讨论.

  • 我意识到这可能只是一个简化的测试用例,但这也可能是使用更具描述性的函数名称的一个例子.他们可能不太可能因为其他事情而感到困惑. (2认同)