如何将子例程作为参数传递给另一个子例程

时间:2016-10-21 06:29:22

标签: perl subroutine

我想将一个子程序作为参数传递给另一个子程序。

子程序question应作为参数传递给子程序answer?我怎么能用Perl做到这一点?

question();

sub question {
    print "question the term";
    return();
}

sub answer() {
    print "subroutine question is used as parameters";
    return();
}

1 个答案:

答案 0 :(得分:3)

您可以使用\&subname语法进行子程序引用,然后,您可以轻松地将其作为参数传递给其他子程序,如标量。这在perlsubperlref中有记录。稍后您可以使用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 -> ();