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

2 perl subroutine

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

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

question();

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

sub answer() {
    print "subroutine question is used as parameters";
    return();
}
Run Code Online (Sandbox Code Playgroud)

Aru*_*ngh 5

您可以使用\&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;
} 
Run Code Online (Sandbox Code Playgroud)

或者您可以通过不命名来创建匿名子例程。这可能会导致有趣的情况closures

my $question = sub  {
                        print "question the term";
                        return 1;
                     };
answer($question);

# you can call it using arrow operator later.
$question -> ();
Run Code Online (Sandbox Code Playgroud)

  • *“这可能会导致有趣的关闭案例”*这是不相关且断章取义的。这里没有关闭。 (2认同)