Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

mapping two arrays into a hash

by Anonymous Monk
on Feb 26, 2003 at 20:48 UTC ( #238909=perlquestion: print w/replies, xml ) Need Help??
Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I have two arrays that have the same number of elements and each element of the first array corresponds to the same number element in the second. I used the following bit of code to put them into a hash, but there has to be a neater way of doing so.
#!/usr/bin/perl -w use strict; my @array1 = qw(a b c); my @array2 = qw(1 2 3); my %hash; for(0..$#array1){ $hash{$array1[$_]}=$array2[$_]; }
How would I use map to accomplish the same thing?

Replies are listed 'Best First'.
(z) Re: mapping two arrays into a hash
by zigdon (Deacon) on Feb 26, 2003 at 20:52 UTC
    Why use map when a slice would do?
    @hash{@array1} = @array2;

    -- zigdon

Re: mapping two arrays into a hash
by tachyon (Chancellor) on Feb 26, 2003 at 21:10 UTC

    A slice is the go but TIMTOWDI

    # slice @hash{@ary1} = @ary2; # map %hash = map { $ary1[$_], $ary2[$_] } 0..$#ary1;

    cheers

    tachyon

    s&&rsenoyhcatreve&&&s&n.+t&"$'$`$\"$\&"&ee&&y&srve&&d&&print

Re: mapping two arrays into a hash
by integral (Hermit) on Feb 26, 2003 at 21:12 UTC
    Zigdon's answer shows the very simple (and good) way to do it, but as you ask you can do this using map to interleave the two arrays (this might be useful for other data structures too).
    my (%hash, @a, @b); %hash = map { ($a[$_], $b[$_]) } 0..$#a;
    Update: This is the same as tachyon's code.

    Although as always TMTOWTDI applies, and you can do it with other loops, although the one below is destructive:

    my (%hash, @a, @b); $hash{shift @a} = shift @b while (@a and @b);

    --
    integral, resident of freenode's #perl
    
Re: mapping two arrays into a hash
by OM_Zen (Scribe) on Feb 26, 2003 at 22:05 UTC
    Hi ,

    #This is with map as both arrays are of same length %hashofarray = map { $array1[$_] => $array2[$_] }0..$#array1; #This is a way to use arrays for building hash @hashofarray{@array1} = @array2;

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://238909]
Approved by zigdon
help
Chatterbox?
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others browsing the Monastery: (8)
As of 2018-06-18 18:23 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Should cpanminus be part of the standard Perl release?



    Results (110 votes). Check out past polls.

    Notices?