user7017426
user7017426

Reputation:

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

Upvotes: 3

Views: 1287

Answers (1)

Arunesh Singh
Arunesh Singh

Reputation: 3535

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

Upvotes: 7

Related Questions