Answer the question
In order to leave comments, you need to log in
How does a multivalued hash work?
While analyzing examples of working with hashes in perl,
I could not understand such an example of working with a multi-valued hash:
%ttys=();
open (WHO, "who|");
while(){
($user, $tty) = split;
push(@ {$ttys{$user}}, $tty);
}
foreach $user (sort keys %ttys){
print "$user: @{$ttys{$user}}\n"
}
push(@ {$ttys{$user}}, $tty);
Answer the question
In order to leave comments, you need to log in
It is for this structure.
push takes two arguments, an array ( @{$ttys{$user}}
) and a value to add ( $tty
)
what kind of animal is that @{$ttys{$user}}
? $ttys{key}
means that we are working with a scalar corresponding to the key key @{$ref}
getting an array by reference.
Together, it turns out like this: take the value from the ttys hash by the $user key and dereference the resulting link as an array.
To study a pearl, you can read a camel or if it's too much a llama ( shop.oreilly.com/product/9780596000271.do and shop.oreilly.com/product/9781565920422.do) Namely, such complex structures are well described in shop.oreilly.com /product/0636920012689.do
At one time, the book "Perl. Special Handbook" by S. Holzner helped me deal with such structures at the initial stage.
And by the way, your code is not very good. Compare with this:
#!/usr/bin/env perl
use strict;
use warnings;
use Data::Dumper;
my %ttys;
open my $WHO, '-|', '/bin/who' or die "open() error: $!\n";
while (<$WHO>) {
my ($user, $tty) = split;
push @{$ttys{$user}}, $tty;
}
close $WHO;
#print Dumper(\%ttys);
foreach my $user (sort keys %ttys) {
print "$user: @{$ttys{$user}}\n";
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question