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

Hi, two similar questions. I found out that one can do the following to pass parameters to references of functions:
my $ref = \&test; $ref->(1); sub test{ print "param: ", shift,"\n"; }
But how to pass the parameter without introducing the variable $ref (i.e., something like \&test->(1))? And how to pass parameters to anonymous subs? Thanks.

Replies are listed 'Best First'.
Re: How to pass parameters to anonymous subs and sub references?
by jdporter (Paladin) on Nov 08, 2004 at 19:41 UTC
    For q1, all you need is parens:
    (\&test)->(1);
    As for q2: Do you have an anonymous sub? What's it look like? In the typical situation, you have a ref to the sub, e.g.
    my $ref = sub { print "(@_)\n" };
    in which case you do as you already showed:
    $ref->(1);
    If not that, then what?
Re: How to pass parameters to anonymous subs and sub references?
by BrowserUk (Patriarch) on Nov 08, 2004 at 19:47 UTC
    sub { print "@_"; }->( qw[ hello world ] ); hello world

    Examine what is said, not who speaks.
    "Efficiency is intelligent laziness." -David Dunham
    "Think for yourself!" - Abigail
    "Memory, processor, disk in that order on the hardware side. Algorithm, algorithm, algorithm on the code side." - tachyon
Re: How to pass parameters to anonymous subs and sub references?
by pg (Canon) on Nov 08, 2004 at 19:50 UTC

    Something similar to what jdporter sort of mentioned when he was answering your question 2... A typical way to assign callback functions when you use Tk (or whatever ...) is:

    my $b = $mw->Button(-command => sub {foo("abc", "123")});

    Not much as passing parameters to anonymous sub, but rather you were forced to create anonymous sub.

Re: How to pass parameters to anonymous subs and sub references?
by Arunbear (Prior) on Nov 08, 2004 at 19:52 UTC
    Also
    &{\&test}(1); &{sub { print "param: $_[0]\n" }}(1);
Re: How to pass parameters to anonymous subs and sub references?
by NetWallah (Canon) on Nov 08, 2004 at 22:10 UTC
    Simpler ..
    my $x=sub{print shift}; &$x('this that');

        Earth first! (We'll rob the other planets later)