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

This is my first question here, so apologies if it's all wrong and/or in the wrong place... but here goes: I have two arrays, and I want to join them in a hash so that one of them becomes the keys, and the other becomes the values. Of course, they should be mapped onto each other, so that $array1[0] gets mapped onto $array2[0], etcetera. What is the simplest, yet most robust way to do this? Thanks a lot! Cheers, Paz

Replies are listed 'Best First'.
Re: Merging arrays into a hash
by japhy (Canon) on Jun 15, 2001 at 15:46 UTC
    You want hash slices. They're so very tasty.
    my %hash; @hash{@keys} = @values;
    Change the arrays to suit your needs.

    japhy -- Perl and Regex Hacker
      Thanks for your replies, I didn't think I would get so many answers so fast! I hope I will soon be able to answer some questions myself and so help other newbies like myself out... Cheers, Paz
Re: Merging arrays into a hash
by Masem (Monsignor) on Jun 15, 2001 at 15:46 UTC
    Use hash slices (briefly mentioned in perldata, but you can probably find more by searching PM for details:
    my %hash; @hash{ @array2 } = @array1;

    Dr. Michael K. Neylon - mneylon-pm@masemware.com || "You've left the lens cap of your mind on again, Pinky" - The Brain
      Thanks for your replies, I didn't think I would get so many answers so fast! I hope I will soon be able to answer some questions myself and so help other newbies like myself out... Cheers, Paz
Re: Merging arrays into a hash
by dimmesdale (Friar) on Jun 15, 2001 at 20:05 UTC
    The above code is very good, and will work for most situations. However, a problem arises if multiple elements of $ary1 have the same value--in which case the last such value assigned to the hash will stick. If this is not the desired effect, then more coding will be needed (and even this assumes that the two arrays have the same amount of elements, or in least @ary2 is larger). For your code, replace the else statement assignment with however you wish to deal with the data (now it is colon separated, but you may desire something else, or even a hash of arrays to store the multiple values).
    for(0..$#ary1) { unless (exists $hash{$ary1[$_]}) { $hash{$ary1[$_]} = $ary2[$_] } else { $hash{$ary1[$_]} = "$hash{$ary1[$_]:$ary2[$_]" } }
Re: Merging arrays into a hash
by marcink (Monk) on Jun 15, 2001 at 15:50 UTC
    This will work:
    #!/usr/bin/perl -w use strict; my @a = qw( 1 2 3 4 5 ); my @b = qw( a b c d e ); my %h = map { $a[$_] => $b[$_] } ( 0..$#a ); print "$_ => $h{$_}\n" foreach sort keys %h;


    I'm still trying to find a way to do this without using indexes, though ;-)

    Update: Yeah, the code japhy and Masem posted does exactly what I was looking for.
    That's what happens when you're too far from your copy of The Camel Book ;-)

    -mk