Question

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?

Was it helpful?

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.

OTHER TIPS

The problem you have, as has already been pointed out, is that s() is interpreted as the s/// substitution operator. Prefixing the function name with an ampersand is a workaround, although I would not say necessarily the correct one. In perldoc perlsub the following is said about calling 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.

What the ampersand does here is merely to distinguish between the built-in function and your own.

The "proper" way to deal with this, apart from renaming your subroutine, is to realize what's going on under the surface. When you say

s();

What you are really saying is

CORE::s();  

When what you mean is

main::s();
 my $s = 's'->();

works too--oddly enough with strict on.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top