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

All the documentation on hashes that i've seen tells you to declare them like so..
my %things = ( "torch" => "red", "banana" => "yellow" );
etc. but i want to create a %hash from two arrays (@people, @jobs), and i want @people to old the keys. How can i do this ???

update (broquaint): title change (was hashes)

Replies are listed 'Best First'.
Re: hashes
by broquaint (Abbot) on Dec 03, 2002 at 12:05 UTC
    You could populate it with a hash slice
    my %hash; @hash{@people} = @jobs;
    Or with map
    my %hash = map { $people[$_] => $jobs[$_] } 0 .. $#people;
    Finally a Haskell-esque approach
    use Functional; my %hash = @{ zip(\@people, \@jobs) };
    All these examples assume both arrays are of the same length and that each index in the arrays correspond to the relative index in the other array (e.g $people[0] corresponds to $jobs[0]).
    HTH

    _________
    broquaint

Re: Populating a hash with two arrays
by pike (Monk) on Dec 03, 2002 at 13:10 UTC
    How about:

    $jobs{shift @people} = shift @jobs while (@people && @jobs);

    Obviously, TIMTOWTDI

    pike

Re: hashes
by Jaap (Curate) on Dec 03, 2002 at 12:14 UTC
    And there's the brain-dead method:
    my %things; for (my $i = 0; $i < @people; $i++) { $things{$people[$i]} = $jobs{$i}; }

      This would be brain-dead only for Monks with a C background ;--)

      A little more perlish would be a loop similar to broquaint's map:

      my %hash; for my $i (0..$#people) { $hash{$people[$i]} = $jobs[$i]; }

      If you don't care about emptying @jobs you can also do:

      my %hash; foreach my people (@people) { $hash{$people}= shift @jobs; }

      But really the hash slice is the most compact way to do it.