gps sago gps sago - 1 month ago 12
Perl Question

How to pass one subroutine as parameters to another subroutine in perl?




I want to pass one subroutine as another subroutien parametes .How can i do it with perl?

i.e

1.sub routine question should be passed as parameter inside the 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 -> ();