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

Is there a perlish way to take two arrays and create a hash? I can't see how to do it with  map. Here's what I am after, demonstrated via an explicit  while loop... which also (yuck) destroys the two arrays...
use strict; use warnings; use Data::Dumper; my @a = qw(one two three four); my @b = qw(1 2 3 4); my %x; while (@a) {$x{pop(@a)} = pop(@b);} # THIS IS THE LINE print Dumper(\%x);
Thanks!
nop

Replies are listed 'Best First'.
(jcwren) RE: Perlish array to hash
by jcwren (Prior) on Nov 06, 2000 at 05:19 UTC
    Slices are your friend!

    Notice for this to work with 'use strict' (and you wouldn't *dare* not use 'use strict', would you?), you can't declare AND initialize the hash in the same statement.

    And for those of you that wonder what happens if the length of @a is unequal to that of @b (which was me, up until a few minutes ago), if @a is longer, the values that exist at positions greater than the length of @b will be inserted into hash as keys, and the value set to undefined. If @b is longer than @a, values that exist at positions greater than the length of @a are discarded/ignored.
    #!/usr/local/bin/perl -w use strict; use Data::Dumper; { my @a = qw(one two three four); my @b = qw(1 2 3 4); my %hash = (); @hash {@a} = @b; print Dumper ([\%hash]); }

    $VAR1 = [ { 'three' => 3, 'two' => 2, 'one' => 1, 'four' => 4 } ];
    --Chris

    e-mail jcwren
      Thanks! Just what I was looking for.
      (And as for strict and warnings, I've seen the light; I am a believer. <g> )
Re: (jptxs) Perlish array to hash
by jptxs (Curate) on Nov 06, 2000 at 05:27 UTC

    jcwren beat me to it, but I was proud I knew this so I'm leaving it up : P

    use strict; my @a = qw(a b c d e f); my @n = qw(1 2 3 4 5 6); my %hash; @hash{@a} = @n; print "$hash{a} $hash{e}\n\n";
    outputs:
    jptxs:/home/jptxs $ perl -w 2arrayHash 1 5 jptxs:/home/jptxs $
    basically @hash tells perl to treat the hash as an array which means feeding it keys creates a slice just like @array[5,8,12] might. this assumes that you have two arrays of the same length, though. are you sure you do?

    Update: the ever wise and vigilent chromatic has reminded me that a slice is a list and not an array - meaning it functions like something which is returned in list context, not like a set of values stored in and array. you could set that list equal to an array to access it later, but that is not what happens automatically. So don't expect to take a slice like @array[4..7] or @hash{@a} and find the value neatly tucked away anywhere for your use unless you make my @array_from_slice = @hash{@a};

    "sometimes when you make a request for the head you don't
    want the big, fat body...don't you go snickering."
                                             -- Nathan Torkington UoP2K a.k.a gnat