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. | [reply] |
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! | [reply] [d/l] [select] |
my %ttys= ();
open( WHO, "who|" )
or die "Can't fork to read from who: $!";
while( <WHO> ) {
my( $user, $tty )= split;
if( ! exists $ttys{$user} ) {
$ttys{$user}= [$tty];
} else {
push @{$ttys{$user}}, $tty;
}
}
foreach my $user ( sort keys %ttys ) {
print "$user: @{$ttys{$user}}\n";
}
The if shows a bit of what happens under the covers in the previous example.
-
tye
(but my friends call me "Tye") | [reply] [d/l] [select] |
| [reply] |
That's what I was asking in my original post,"I've read about references from several sources; I think referencing the arrays are my answer, but I'm just not getting it."
| [reply] |