如何将子程序作为参数传递给另一个子程序 [英] How to pass a subroutine as a parameter to another subroutine

查看:49
本文介绍了如何将子程序作为参数传递给另一个子程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to pass a subroutine as a parameter to another subroutine.

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

Subroutine question should be passed as parameter to subroutine answer? How can I do it with Perl?

question();

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

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

推荐答案

您可以使用 \&subname 语法获取子程序引用,然后,您可以轻松地将其作为参数传递给其他子程序,例如标量.这在 perlsubperlref.稍后您可以使用 Arrow operator(->).

You can take subroutine reference using \&subname syntax and then, you can easily pass it to other subroutine as arguments like a scalar. This is documented in 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

Or you can create an anonymous subroutine by not naming it. It may lead to interesting case of closures

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

# you can call it using arrow operator later.
$question -> ();

这篇关于如何将子程序作为参数传递给另一个子程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆