monkfan has asked for the wisdom of the Perl Monks concerning the following question:

Given this plain array, one would obtain a hash by array slice easily.
use Data::Dumper; my @array = ( 0, 1, 2, 3, 4, 5 ); my %uniq; @uniq{@array[1..$#array]} = (); print Dumper \%uniq;
Yielding:
$VAR1 = { '4' => undef, '1' => undef, '3' => undef, '2' => undef, '5' => undef };
But how can one achieve the same result, if what we have is AoA. I tried the following but doesn't work:
use Data::Dumper; my %uniq; my @aoa = ( ['foo',0], # Changed from 'AoA' to 'aoa'. Thanks to bobf. ['foo',1], ['foo',2], ['foo',3], ['foo',4], ['foo',5],); @uniq{ @aoa[ 1 ... $#aoa ]->[-1] } = (); print Dumper \%uniq;
Which prints the wrong:
$VAR1 = { '5' => undef };

Regards,
Edward

Replies are listed 'Best First'.
Re: Transforming AoA to Hash by Array Slicing
by rhesa (Vicar) on Aug 08, 2006 at 03:01 UTC
    Unfortunately, that notation doesn't work. Perl5 isn't Ruby (yet).

    You'll need to unroll the array somehow. I'll leave it up to you to decide if the following is a readable solution:

    @uniq{ map { $_->[-1] } @AoA } = ();

    Update: of course, when we're going that way, we might as well be explicit about it and just say:

    my %uniq = map { $_->[-1] => 1 } @AoA;
Re: Transforming AoA to Hash by Array Slicing
by bobf (Monsignor) on Aug 08, 2006 at 03:41 UTC

    First, please use strict. Your example declares and sets @AoA, then you try to slice @aoa.

    AFAIK, rhesa is correct - you need to use something like his code to get what you want. The reason is because the slice @aoa[ 1 ... $#aoa ] returns a list of array references. As per perldata a list evaluated in scalar context returns the last element, and per perlref "the left side of the arrow can be any expression returning a reference". Therefore you dereference only the last element of that list with ->[-1], which yields only a single value for the list in the slice on %uniq. You can use map as rhesa described to dereference each array ref and create a list for the slice on %uniq.