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

How to pass a subroutine as a parameter to another subroutine

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

子例程 question 应该作为参数传递给子例程 answer?我怎样才能用 Perl 做到这一点?

question();

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

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

您可以使用 \&subname 语法获取子例程引用,然后您可以轻松地将其作为标量等参数传递给其他子例程。这记录在 perlsub and perlref. Later you can dereference it using 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 -> ();