5.7. Hashes with Multiple Values Per KeyProblemYou want to store more than one value for each key. Solution
Store an array reference in Discussion
You can only store scalar values in a hash. References, however, are scalars. This solves the problem of storing multiple values for one key by making This code shows simple insertion into the hash. It processes the output of who (1) on Unix machines and outputs a terse listing of users and the ttys they're logged in on: %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 heart of the code is the foreach $user (sort keys %ttys) { print "$user: ", scalar( @{$ttys{$user}} ), " ttys.\n"; foreach $tty (sort @{$ttys{$user}}) { @stat = stat("/dev/$tty"); $user = @stat ? ( getpwuid($stat[4]) )[0] : "(not available)"; print "\t$tty (owned by $user)\n"; } }
sub multihash_delete { my ($hash, $key, $value) = @_; my $i; return unless ref( $hash->{$key} ); for ($i = 0; $i < @{ $hash->{$key} }; $i++) { if ($hash->{$key}->[$i] eq $value) { splice( @{$hash->{$key}}, $i, 1); last; } } delete $hash->{$key} unless @{$hash->{$key}}; } The alternative approach to multivalued hashes is given in Chapter 13, Classes, Objects, and Ties , implemented as tied normal hashes. See Also
The Copyright © 2002 O'Reilly & Associates. All rights reserved. |
|