我想将一个子程序作为参数传递给另一个子程序。
子程序question
应作为参数传递给子程序answer
?我怎么能用Perl做到这一点?
question();
sub question {
print "question the term";
return();
}
sub answer() {
print "subroutine question is used as parameters";
return();
}
答案 0 :(得分:3)
您可以使用\&subname
语法进行子程序引用,然后,您可以轻松地将其作为参数传递给其他子程序,如标量。这在perlsub
和perlref
中有记录。稍后您可以使用Arrow operator(->)
取消引用它。
sub question {
print "question the term";
return 1;
}
my $question_subref = \&question;
answer($question_subref);
sub answer {
my $question_subref = shift;
print "subroutine question is used as parameters";
# call it using arrow operator if needed
$question_subref -> ();
return 1;
}
或者您可以通过不命名来创建匿名子例程。这可能会导致closures
my $question = sub {
print "question the term";
return 1;
};
answer($question);
# you can call it using arrow operator later.
$question -> ();