tip : array nx2 to hash in one line

tip : array nx2 to hash in one line

am 09.05.2007 15:44:32 von George

# nothing great, just how to convert an nx2 array of arrays to a hash in one
line.

my @array = ( ['k1','v1'], ['k2','v2'], ['k3','v3'] );

my %hash;
@hash{map{$_->[0]}@array}=map{$_->[1]}@array;

print $hash{'k2'}

Re: tip : array nx2 to hash in one line

am 09.05.2007 16:24:18 von Paul Lalli

On May 9, 9:44 am, "George" wrote:
> # nothing great, just how to convert an nx2 array of arrays to a hash in one
> line.
>
> my @array = ( ['k1','v1'], ['k2','v2'], ['k3','v3'] );
>
> my %hash;
> @hash{map{$_->[0]}@array}=map{$_->[1]}@array;
>
> print $hash{'k2'}

Wow. That's incredibly over-complicated and illegible.

my @array = ( ['k1','v1'], ['k2','v2'], ['k3','v3'] );
my %hash = map { @{$_} } @array;

Paul Lalli

Re: tip : array nx2 to hash in one line

am 09.05.2007 16:51:25 von someone

Paul Lalli wrote:
> On May 9, 9:44 am, "George" wrote:
>># nothing great, just how to convert an nx2 array of arrays to a hash in one
>>line.
>>
>>my @array = ( ['k1','v1'], ['k2','v2'], ['k3','v3'] );
>>
>>my %hash;
>>@hash{map{$_->[0]}@array}=map{$_->[1]}@array;
>>
>>print $hash{'k2'}
>
> Wow. That's incredibly over-complicated and illegible.
>
> my @array = ( ['k1','v1'], ['k2','v2'], ['k3','v3'] );
> my %hash = map { @{$_} } @array;

And that has too much punctuation. :-)

my @array = ( ['k1','v1'], ['k2','v2'], ['k3','v3'] );
my %hash = map @$_, @array;



John
--
Perl isn't a toolbox, but a small machine shop where you can special-order
certain sorts of tools at low cost and in short order. -- Larry Wall

Re: tip : array nx2 to hash in one line

am 09.05.2007 21:36:19 von Paul Lalli

On May 9, 10:51 am, "John W. Krahn" wrote:
> Paul Lalli wrote:
> > On May 9, 9:44 am, "George" wrote:
> >># nothing great, just how to convert an nx2 array of arrays to a hash in one
> >>line.
>
> >>my @array = ( ['k1','v1'], ['k2','v2'], ['k3','v3'] );
>
> >>my %hash;
> >>@hash{map{$_->[0]}@array}=map{$_->[1]}@array;
>
> >>print $hash{'k2'}
>
> > Wow. That's incredibly over-complicated and illegible.
>
> > my @array = ( ['k1','v1'], ['k2','v2'], ['k3','v3'] );
> > my %hash = map { @{$_} } @array;
>
> And that has too much punctuation. :-)
>
> my @array = ( ['k1','v1'], ['k2','v2'], ['k3','v3'] );
> my %hash = map @$_, @array;

Nah, it was very specifically the way I wanted it. I hate the "drop
the { } if the reference is a simple scalar" shortcut, because people
inevitably forget the "if" part of that. And I always prefer block-
map over expression-map, because of the case in which your EXPR is
actually a hash reference that you want to create, and Perl guesses
wrong, thinking you're using block-syntax. If you get into the habbit
of using block at all times, you'll know to use a double { { for
hashref-within-block, and avoid the ambiguity.

Paul Lalli