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

Replies are listed 'Best First'.
Re^2: return more than 1 value
by changma_ha (Sexton) on Jul 29, 2010 at 08:59 UTC

    Thank you a lots Utilitarian....your example made my doubt clear..i will ask you..if i have any problems.

Re^2: return more than 1 value
by changma_ha (Sexton) on Jul 30, 2010 at 06:06 UTC

    @ Utilitarian,i have another question regarding a line of your code. in @returned_values{@{$keys}} = @{$values}; how did u take a %returned_values as an array? i mean i am not getting this line properly. Thanks in advance

      @hash{@array_of_keys}=@array_of_values;
      Is the Perlish way of assigning an array of values to their equivalent keys. You could, (if you enjoy typing), write
      for my $index (0..$#array_of_keys){ $hash{$array_of_keys[$index]}=$array_of_values[$index]; }
      In the line you cite there isn't an array @returned_values it is a hash slice. take a look at the perldata man page for further, better presented, info

      print "Good ",qw(night morning afternoon evening)[(localtime)[2]/6]," fellow monks."
A reply falls below the community's threshold of quality. You may see it by logging in.