in reply to return more than 1 value
Hi changma_ha,
There are a few issues in your code, as pointed out above you can only return from a subroutine once so the second return is meaningless.
However if you return two arrays they are "flattened" and become indistinguishable. Take a look at the return documentation
As a result you should return references to the two arrays (or other data structure)
I have provided you with a code sample with comments which should make things clearer, play about with it and feel free to ask if you don't follow what it is doing.
use strict; use warnings; my @list =qw (1 2 3 4 5); # define a hash to take back the values my %returned_values; # get the array references my ($keys, $values) = apackage::ahash(@list); # Put them in a hash @returned_values{@{$keys}} = @{$values}; # print out for my $key (@{$keys}){ print "$key maps to $returned_values{$key} \n"; } package apackage; sub ahash{ my %hash; # You are calling the subroutine with an uneven number of elements, # You should check for this and correct before assigning to a hash if ((@_ % 2) != 0){ push (@_,"null"); } %hash = @_ ; # Your foreach loop made no sense here my @ke = keys %hash; my @val = values %hash; # return references to your two arrays return (\@ke, \@val); # in this context returning a hash makes more sense }
print "Good ",qw(night morning afternoon evening)[(localtime)[2]/6]," fellow monks."
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^2: return more than 1 value
by changma_ha (Sexton) on Jul 29, 2010 at 08:59 UTC | |
Re^2: return more than 1 value
by changma_ha (Sexton) on Jul 30, 2010 at 06:06 UTC | |
by Utilitarian (Vicar) on Jul 30, 2010 at 07:16 UTC | |
A reply falls below the community's threshold of quality. You may see it by logging in. |
In Section
Seekers of Perl Wisdom