gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 20:56:16 24 4
gpt4 key购买 nike

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

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

question();

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

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

最佳答案

您可以使用 \&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 -> ();

关于perl - 如何将一个子程序作为参数传递给另一个子程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40169771/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com