http://qs321.pair.com?node_id=851882


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."