Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

return data from a subroutine reference...

by abachus (Monk)
on Aug 12, 2006 at 07:34 UTC ( #567010=perlquestion: print w/replies, xml ) Need Help??

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

hello all,

I'd like to use something like the following code, but how does one get a return value from a call like that ?

my %arch=( apple => \&mac, sun => \&sparc, hp => \&parisc ); my $type='sun'; if(exists $arch{$type}) { $arch{$type}->("some stuff"); # Where / how to get the returned data ? } else { exit; } sub mac { return(0); } sub sparc { return(1); } sub parisc { return(2); }
thanks,

Isaac.

Replies are listed 'Best First'.
Re: return data from a subroutine reference...
by bobf (Monsignor) on Aug 12, 2006 at 07:43 UTC

    $arch{$type}->("some stuff") simply calls the subroutine (see perlref), so you can capture the return value from it just as you would any other subroutine:

    my $retval = $arch{$type}->("some stuff");

    Update: You may also find Implementing Dispatch Tables helpful (from our Tutorials section).

Re: return data from a subroutine reference...
by perlfan (Vicar) on Aug 12, 2006 at 13:14 UTC
    You can treat an anonymous sub as any other - everything on the right hand side of the assignment operator (=) is just some jibberish to call the subroutine. Any return values you get are still passed back the same way.
Re: return data from a subroutine reference...
by aufflick (Deacon) on Aug 13, 2006 at 07:08 UTC
    The above posters are correct - sometimes the answer is just too obvious right! If you haven't come across it yet, one of Perl's guiding principles is DWIM (Do What I Mean). In other words if you don't know how to express something in Perl, just try what seems natural - you'd be surprised just how often that works!

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others scrutinizing the Monastery: (1)
As of 2022-08-09 23:05 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?