As per my sample code below, there are two styles to call a subroutine: subname and subname().
#!C:\Perl\bin\perl.exe
use strict;
use warnings;
use 5.010;
&marine(); # style 1
&marine; # style 2
sub marine {
state $n = 0; # private, persistent variable $n
$n += 1;
print "Hello, sailor number $n!\n";
}
Which one, &marine(); or &marine;, is the better choice if there are no arguments in the call?
In Learning Perl, where this example comes from, we’re at the very beginning of showing you subroutines. We only tell you to use the
&so that you, as the beginning Perler, don’t run into a problem where you define a subroutine with the same name as a Perl built-in then wonder why it doesn’t work. The&in front always calls your defined subroutine. Beginning students often create their own subroutinelogto print a message because they are used to doing that in other technologies they use. In Perl, that’s the math function builtin.After you get used to using Perl and you know about the Perl built-ins (scan through perlfunc), drop the
&. There’s some special magic with&that you hardly ever need:You can leave off the
()if you’ve pre-declared the subroutine, but I normally leave the()there even for an empty argument list. It’s a bit more robust since you’re giving Perl the hint that themarineis a subroutine name. To me, I recognize that more quickly as a subroutine.