Reputation: 105
I am new to Perl language, and in the code I am using there is this line :
$BASEDIR = &getcwd();
I am wondering why there is a &
in front of the call to getcwd
, and I could not find any reference about that. Could someone help me with this ?
Thanks a lot !
Upvotes: 3
Views: 159
Reputation: 3705
Short answer is that it is optional unless you are running a really old version of perl.
For more detail see the perlsub man page (run perldoc perlsub
or man perlsub
depending on your environment)
A subroutine may be called using an explicit "&" prefix. The "&" is optional in modern Perl, as are parentheses if the subroutine has been predeclared. The "&" is not optional when just naming the subroutine, such as when it's used as an argument to defined() or undef(). Nor is it optional when you want to do an indirect subroutine call with a subroutine name or reference using the "&$subref()" or "&{$subref}()" constructs, although the "$subref->()" notation solves that problem. See perlref for more about all that.
Upvotes: 2
Reputation: 385657
It causes the subroutine's prototype to be ignored.
$ perl -e'
sub f($@) { print("@_\n"); }
my @a = (4,5,6);
f(4,5,6);
f(@a);
&f(@a);
'
4 5 6
3
4 5 6
But that's probably not the reason it's used here. After all, Cwd::getcwd
doesn't have a prototype. &
can't be used on named operators (i.e. the functions of perlfunc, e.g. print
), so some beginners use it on subroutines to distinguish them from operators. I believe this is a practice recommended by a popular Perl book.
Upvotes: 7