Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot

Re: Return value from function

by lyklev (Pilgrim)
on Jul 12, 2007 at 21:26 UTC ( #626321=note: print w/replies, xml ) Need Help??

in reply to Return value from function

If you are returning a simple, short list of values, or even a hash, returning the values is probably the best, because it is the simplest.


my @values = f(...); # simple read, # @values is a copy
my %hash = f(...); # hash is also a copy my $value = $hash{'value'};
makes a copy of all values, so if you return a lot of values, you might have some performance issues. In that cast, a reference might be faster.

If you want to return more than one array or arrays and hashes where the returned lengths are unknown, references are your only choice:

my (@v1, @v2) = f(...);
makes @v1 slurp all return values, leaving @v2 empty. Solution, with a few comments:
sub f { (...) return \@v1, \@v2, \%v3; # return 2 array and a hash # reference } my ($ar1, $ar2, $hr3) = f(); # collect references my @ar1 = @{ $ar1 }; # get the first array, # creating a duplicate foreach (@ {$ar2} ) {...} # avoid copying the array, # probably more efficient my $value = $hr3->{'value'} # some people find this # notation cumbersome # and avoid references

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://626321]
and God said, "Let Newton be!"...

How do I use this? | Other CB clients
Other Users?
Others exploiting the Monastery: (8)
As of 2018-07-16 07:10 GMT
Find Nodes?
    Voting Booth?
    It has been suggested to rename Perl 6 in order to boost its marketing potential. Which name would you prefer?

    Results (333 votes). Check out past polls.