R
R
ReD2016-04-25 12:58:52
Perl
ReD, 2016-04-25 12:58:52

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"
}

I do not quite understand how the placement in the array occurs:
push(@ {$ttys{$user}}, $tty);
Please explain!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
vaut, 2016-04-25
@trinitr0

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

K
krypt3r, 2016-04-25
@krypt3r

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 question

Ask a Question

731 491 924 answers to any question