Subroutines also have references, as well as anonymous subroutines. Suppose you already have an array, hash reference knowledge, so here is a brief introduction.
$ref_sub = \&mysub; # Subprogram reference, & symbol must be less
&{$ref_sub}(ARGS) # Release the subroutine reference, pass the parameter ARGS
&$ref_sub(ARGS) # Resolve subroutine reference
$ref_sub->(ARGS) # Resolve subroutine reference
$ref_sub->() # Pass null parameter
Sub {...}; # Define anonymous subroutine, no name after sub
$ref_sub = sub {...}; # Anonymous subroutine reference
With the subroutine reference, you can invoke the subroutine on demand.
For example:
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->();
}
Change to Anonymous subroutine:
$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";
$$_->();
}
Even, use the anonymous subroutine as part of the data structure:
%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->();
}
The maximum effect of subroutine references and anonymous subroutines may be for callback functions (callback), closures (closure). This topic is a bit big, see the next article.
Perl subroutine references and anonymous subroutines