Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

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

by Limo (Scribe)
on Sep 19, 2000 at 19:40 UTC ( [id://33104]=note: print w/replies, xml ) Need Help??


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

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.

Replies are listed 'Best First'.
RE: RE: RE: Re: Populating a Hash: Can someone help me to understand?
by merlyn (Sage) on Sep 19, 2000 at 19:43 UTC
      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.
        Okay. I think I see what you're trying to do now. Based on what I see in the Cookbook on p 140, it looks like you want a hash whose values are array refs. This will effectively get you the "more than one value per hash key" that you're looking for. It is kind of hard to tell what to help you with regarding that particular example without a little smaller target for us to aim for.
        The example is fairly simple, except for the fact that instead of assigning values to an array, then setting the array reference to a hash key, it pushes values directly into the hash.
        BTW: here is the code I'm referring to:
        %ttys = (); open(WHO,"who|") or die "can't open who: $!"; while (<WHO>) { ($user, $tty) = split; push( @{$ttys{$user}}, $tty); } foreach $user (sort keys %ttys) { print "$user: @{$ttys{$user}}\n"; }

        The one line that looks like it might cause understanding problems is push( @{$ttys{$user}}, $tty); Basically, push expects a list for its forst argument, but $ttys{$user} will return a list refernce, not a list. Using @{...} forces push to evaluate what's in those braces as a list, which it knows how to work with.

        Guildenstern
        Negaterd character class uber alles!

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others admiring the Monastery: (7)
As of 2024-04-19 08:37 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found