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

I have an array of arrays which have single elements, and I want a hash using these as keys, I came up with this, but is there a better way?
my $ranksUsed = [ [ 1 ], [ 2 ] ]; my @ranksUsed; for (@$ranksUsed) { push @ranksUsed, $_->[0]; } my %ranksUsed = map {$_ => undef} @ranksUsed;

Replies are listed 'Best First'.
Re: array of arrays to hash
by choroba (Cardinal) on Oct 06, 2014 at 15:06 UTC
    You can use a hash slice to get the same result:
    #!/usr/bin/perl use warnings; use strict; use Test::More tests => 1; my $ranksUsed = [ [ 1 ], [ 2 ] ]; sub original { my @ranksUsed; for (@$ranksUsed) { push @ranksUsed, $_->[0]; } my %ranksUsed = map {$_ => undef} @ranksUsed; return \%ranksUsed } sub slice { my %ranksUsed; undef @ranksUsed{ map @$_, @$ranksUsed }; return \%ranksUsed } is_deeply(original(), slice(), 'same');

    If it's possible for the list to be empty, you need to check for that.

    لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ
Re: array of arrays to hash
by NetWallah (Canon) on Oct 06, 2014 at 17:25 UTC
    This works too:
    my $ranksUsed = [ [ 1 ], [ 2 ] ]; # No intermediate array or loop... my %ranksUsed = map {$_->[0] => undef} @$ranksUsed;
    Produces:
    $VAR1 = { '1' => undef, '2' => undef };

            "You're only given one little spark of madness. You mustn't lose it."         - Robin Williams

      This has the advantage, IMHO, that it produces the same result as the OPed code in the case that the array or any sub-array(s) are empty.

Re: array of arrays to hash
by bitman (Scribe) on May 02, 2017 at 14:19 UTC

    Looking back now ....

    my $ranksUsed = [ [ 1 ], [ 2 ] ]; my %ranksUsed; for (@$ranksUsed) { $ranksUsed{$_->[0]}=undef; }

    No map or sub array.