Wiggins D'Anconia wrote:
> 
> Code sample:
> 
> safe to assume @vals and @heads are predefined and contain equal # of
> values, use strict and use warnings are in place.
> 
> if (wantarray) {
>     return @vals;
> }
> else {
>     # create hash where keys are from @heads and values are from @vals
>     # then return a reference to that hash, only when not in list context
>     my %vals;
>     @vals{@heads} = @vals;
>     return \%vals;
> }
> 
> I was surprised that I could not avoid in the else doing the code in 3
> lines (obviously this isn't a huge deal).

Instead of using two arrays and then converting them to a hash at the
end, why not just store everthing in a hash to begin with?

sub somesub {
    my %hash;

    # store heads and vals in the hash

    if ( wantarray ) {
        return values %hash;
        }
    else {
        return \%hash;
        }
    }

 
> I was looking for something like:
> 
> return my @vals{@heads} = @vals;
> 
> Which didn't work. And this didn't give me the proper hash ref:
> 
> \@vals{@heads} = @vals;
> 
> nor did the following execute, it complained about not being able to
> 'my' the expression:
> 
> my @vals{@heads} = @vals;

$ perl -Mwarnings -Mstrict -le'
sub test {
    my @keys = qw/a b c d/;
    my @vals = qw/1 2 3 4/;

    if ( wantarray ) {
        return @vals;
        }
    else {
        return { map { shift @keys, shift @vals } @vals };
        }
    }

my $x = test;
my @x = test;

print "Key: $_   Value: $x->{$_}" for keys %$x;
print "Array value: $_" for @x;
'
Key: a   Value: 1
Key: b   Value: 2
Key: c   Value: 3
Key: d   Value: 4
Array value: 1
Array value: 2
Array value: 3
Array value: 4



John
-- 
use Perl;
program
fulfillment

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to