Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"
 
PerlMonks  

Re: Populating a Hash: Can someone help me to understand?

by ar0n (Priest)
on Sep 19, 2000 at 19:08 UTC ( #33099=note: print w/replies, xml ) Need Help??


in reply to Populating a Hash: Can someone help me to understand?

(ugly stuff removed, replaced with less ugly)
map { $hash{$keys[$_]} = $vals[$_] } (0..$#keys);

update
but there are nicer, prettier ways to do this; as you'll probably see below...

Replies are listed 'Best First'.
RE: Re: Populating a Hash: Can someone help me to understand?
by merlyn (Sage) on Sep 19, 2000 at 19:11 UTC
    You said:
    while (my $key = shift @keys and my $value = shift @values) { $hash{$key} = $value; }
    And your code stops too quickly if either the key or the value is false.
    You updated:
    while (defined (my $key = shift @keys) and defined(my $value = shift @ +values)) { $hash{$key} = $value; }
    But even adding the defined test as you did doesn't help. Consider @keys = (1, 2, undef, 3, 4);. You'll never get to 3 or 4.

    What would work is:

    while (@keys and @values) { $hash{shift @keys} = shift @values; }

    -- Randal L. Schwartz, Perl hacker

      Hmmm. Something strange here.
      my @array = subroutine($file1, $list1); #foreach my $item(@array) { #print "$item\n"; # }
      Now, when I uncomment the foreach/print block, it prints as intended. However, when I add:
      my %hash; while (@keys and @values) { $hash{shift @keys} = shift @values; } foreach my $k (sort keys %hash) { print "$k => $hash{$k}\n"; }
      the program returns only one value per key, while @values contains several whitespace delimited elements.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://33099]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others examining the Monastery: (7)
As of 2020-06-05 19:47 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Do you really want to know if there is extraterrestrial life?



    Results (40 votes). Check out past polls.

    Notices?