Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

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

by merlyn (Sage)
on Sep 19, 2000 at 19:11 UTC ( #33101=note: print w/replies, xml ) Need Help??


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

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

Replies are listed 'Best First'.
RE: RE: Re: Populating a Hash: Can someone help me to understand?
by Limo (Scribe) on Sep 19, 2000 at 19:40 UTC
    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.
        Well, I AM trying to create a hash with multiple values per key! Apparently, this is possible. I'm referring to "Perl Cookbook", pg. 140. There is an example of this, but I'm having a hard time understanding it.

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others exploiting the Monastery: (4)
As of 2020-05-30 17:43 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    If programming languages were movie genres, Perl would be:















    Results (173 votes). Check out past polls.

    Notices?