Gil Epshtain
Gil Epshtain

Reputation: 9831

Perl - Difference between invoking sub-routine with or without "&" (ampersand)

What is the difference between the next two lines in Perl:

PopupMsg("Hello");

&PopupMsg("Hello");

...

sub PopupMsg
{
    subroutines code here...
}

please notice that in some cases I must use the first line and in some the second, other wise I get an error.

Upvotes: 0

Views: 1361

Answers (2)

Borodin
Borodin

Reputation: 126752

It is bad practice to call subroutines using the ampersand &. The call will compile fine if you use parentheses or have predeclared the symbol as a subroutine name.

The ampersand is necessary when you are dealing with the subroutine as a data item, for instance, to take a reference to it.

my $sub_ref = \&PopupMsg;
$sub_ref->(); # calling subroutine as reference.

Upvotes: 9

mwarin
mwarin

Reputation: 75

See http://perldoc.perl.org/perlsub.html:

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

Prototypes explained further down in http://perldoc.perl.org/perlsub.html#Prototypes.

Upvotes: 4

Related Questions