How to pass a subroutine as a parameter to another subroutine

会有一股神秘感。 提交于 2019-12-24 08:38:43

问题


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

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();
}

回答1:


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;
} 

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 -> ();


来源:https://stackoverflow.com/questions/40169771/how-to-pass-a-subroutine-as-a-parameter-to-another-subroutine

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!