Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

Re: How to call a sub-routine ref

by blue_cowdawg (Monsignor)
on Oct 19, 2012 at 18:34 UTC ( [id://1000012]=note: print w/replies, xml ) Need Help??


in reply to How to call a sub-routine ref

      alling a subroutine from a reference

assuming for a second you are talking about a reference such as

| stuff before my $sref = \&foo | stuff after
then you would call it thusly:
| later &($sref)( arg1....argn); |
where "arg1...argn" would be replaced by the arguments you want passed to the sub.

Here is a more complete example:

#!/usr/bin/perl -w use strict; my $sref=\&foo; &{$sref}; exit(0); sub foo { print "This is foo.\n"; }


Peter L. Berghold -- Unix Professional
Peter -at- Berghold -dot- Net; AOL IM redcowdawg Yahoo IM: blue_cowdawg

Replies are listed 'Best First'.
Re^2: How to call a sub-routine ref
by greengaroo (Hermit) on Oct 19, 2012 at 20:36 UTC

    Yes I know. Here is another example with an anonymous subroutine:

    my $ref = sub { print "Hello World!\n"; }; # Both are equivalent $ref->(); &{$ref}(); # But which one is best? That is the question!

    Also, I don't do simple stuff like that, I have objects and callback functions and so on. Most of the time I have deep structures that returns functions, or objects, then I want to call that function or object method.

    Let me sleep on it and I will try to provide a more concrete example.

    There are no stupid questions, but there are a lot of inquisitive idiots.

      Did you actually test that code?

      $ cat greengaroo.pl use strict; my $ref = sub { print "Hello World!\n"; }; # Both are equivalent $ref->(); &{ref}(); # But which one is best? That is the question! $ perl greengaroo.pl Hello World! Undefined subroutine &main::ref called at greengaroo.pl line 9.

      your second call fails.

      If you fix this by rewriting it thusly:

      &{$ref}();
      there is still the open question of "which is better?" From a readability standpoint I'd vote for the latter rather than the former. Others may disagree but that is the essence of TIMTOWTDI. If you feel there may be a performance issue involved here have you tried profiling the code?


      Peter L. Berghold -- Unix Professional
      Peter -at- Berghold -dot- Net; AOL IM redcowdawg Yahoo IM: blue_cowdawg

        You are right! I forgot a $... sorry about that! Thanks for pointing it!

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1000012]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others learning in the Monastery: (6)
As of 2024-04-23 06:47 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found