Search code examples
perlcompiler-errorssubroutinereserved-words

Why does Perl sub s require &


The following file does not compile:

sub s {
    return 'foo';
}
sub foo {
    my $s = s();
    return $s if $s;
    return 'baz?';
}

The error from perl -c is:

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.

But if I replace s() with &s() it works fine. Can you explain why?


Solution

  • The & prefix definitively says you want to call your own function called "s", rather than any built-in with the same name. In this case, it's confusing it for a substitution operator (like $stuff =~ s///;, which can also be written s()()).

    Here's a PerlMonks discussion about what the ampersand does.