vit has asked for the wisdom of the Perl Monks concerning the following question:

Dear Monks,
I have a sub described explicitly like
sub xxx { my $x1 = shift; my $x2 = shift; print "$x1, $x2\n"; }
I need to pass it into sub yyy and call it from there.
What's the right way to do this? Something like
.............. yyy( <xxx("hi", "i am here")> ) .............. sub yyy { <reference to xxx> = shift; .......... call <xxx>; }

Replies are listed 'Best First'.
Re: Pass sub reference
by Anonymous Monk on Oct 28, 2010 at 17:04 UTC
    For example:

    #!/usr/bin/perl sub xxx { my $x1 = shift; my $x2 = shift; print "$x1, $x2\n"; } sub yyy { my $func = shift; $func->(@_) } yyy( \&xxx, "foo", 42 ); # \&xxx is the sub reference.
      ...or maybe, if you want to pass around the arguments together with the function, you can wrap the call in another sub:

      ... sub yyy { my $func = shift; $func->(); } yyy( sub { xxx("foo", 42) } );

        Which is to say (warning: semi-advanced topic, but not really all that scary): Use a closure. See tutorial Closure on Closures.