子程序也有引用,也有匿名子程序。假设你已经具备了数组、hash的引用知识,所以这里简单介绍一下。
$ref_sub = \&mysub; # 子程序引用,&符号必须不能少 &{$ref_sub}(ARGS) # 解除子程序引用,传递参数ARGS &$ref_sub(ARGS) # 解除子程序引用 $ref_sub->(ARGS) # 解除子程序引用 $ref_sub->() # 传递空参数 sub {...}; # 定义匿名子程序,sub后面没有名称 $ref_sub = sub {...}; # 匿名子程序的引用
有了子程序引用,就可以按需调用子程序。
例如:
sub java_learn { print "Learning Java Now\n"; } sub perl_learn { print "Learning Perl Now\n"; } sub python_learn { print "Learing Python Now\n"; } %sub_hash=( "javaer" => \&java_learn,"perler" => \&perl_learn,"pythoner" => \&python_learn,); while(my ($who,$sub)=each %sub_hash){ print "$who is learning\n"; $sub->(); }
改成匿名子程序:
$javaer = sub { print "Learning Java Now\n"; }; $perler = sub { print "Learning Perl Now\n"; }; $pythoner = sub { print "Learing Python Now\n"; }; foreach (qw(javaer perler pythoner)){ print "$_ is learning\n"; $$_->(); }
甚至,将匿名子程序作为数据结构的一部分:
%sub_hash = ( "javaer" => sub { print "Learning Java Now\n"; },"perler" => sub { print "Learning Perl Now\n"; },"pythoner" => sub { print "Learning Python Now\n"; },); while( my($who,$sub)=each %sub_hash ){ print "$who is learning\n"; $sub->(); }
子程序引用、匿名子程序的最大作用可能是用于回调函数(callback)、闭包(closure)。这个话题有点大,见下一篇文章。