http://qs1969.pair.com?node_id=567010

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!