gps sago gps sago - 1 month ago 4
Perl Question

How to pass a subroutine as a parameter to another subroutine

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

Answer

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