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
  • 7,189
  • 7
  • 50
  • 74
  • 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

5

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

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 = \&PopupMsg;
Dave Sherohman
  • 44,129
  • 13
  • 64
  • 98
Borodin
  • 125,056
  • 9
  • 69
  • 143
3

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
  • 65
  • 7