If the compiler sees the subroutine definition before invocation, or if Perl
can tell from the syntax that it’s a subroutine call, the subroutine can be called without
an ampersand, just like a built-in function. (But there’s a catch hidden in that rule, as
you’ll see in a moment.)
This means that if Perl can see that it’s a subroutine call without the ampersand, from
the syntax alone, that’s generally fine. That is, if you’ve got the parameter list in
parentheses, it’s got to be a function* call:
my @cards = shuffle(@deck_of_cards); # No & necessary on &shuffle
The catch is this: if the subroutine has the same name as
a Perl built-in, you must use the ampersand to call it. With an ampersand, you’re sure
to call the subroutine; without it, you can get the subroutine only if there’s no built-in
with the same name:
如果子函数在被调用之前定义或编译器从上下语法上可以知道他是个自定义函数,可以省略&。从语法上可以理解为,如果给函数加了参数列表,那么可以省&.
- #!/usr/bin/perl -w
-
#
-
use strict;
-
-
great_fun(); # or use &great_fun;
-
-
sub great_fun{
-
print "yes";
-
}
如果自定义函数和built-in函数同名则一定要加&。
- sub chomp {
-
print "Munch, munch!\n";
-
}
-
&chomp; # That ampersand is not
the real rule to use is this one: until you know the names of
all of Perl’s built-in functions, always use the ampersand on function calls.
阅读(370) | 评论(0) | 转发(0) |