0

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.

Gil Epshtain
  • 8,670
  • 7
  • 63
  • 89
  • 1
    Please give an example of when you have to use the second form. – Borodin Mar 12 '14 at 14:06
  • [Perl using the special character &](http://stackoverflow.com/questions/17173783/perl-using-the-special-character/17173958#17173958) – Miller Mar 12 '14 at 18:40

2 Answers2

8

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.
slayer
  • 214
  • 4
  • 11
Borodin
  • 126,100
  • 9
  • 70
  • 144
4

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.

mwarin
  • 75
  • 7