Задача примерно такая: Есть хэш списков %stats. Нужно добавлять элементы в список, хранящийся в $stats{ $key }, Если значение $stats{ $key } не задано, то задать, как список из одного элемента.
Предполагается многократное выполнение этой операции
Решено: Perl Hash of lists
Модератор: Модераторы разделов
-
Poor Fred
- Сообщения: 1575
- Статус: Pygoscelis papua
- ОС: Gentoo Linux, FreeBSD
Re: Решено: Perl Hash of lists
ну а
Код: Выделить всё
$stats{ $key } .= $some_elementили
Код: Выделить всё
push $stats{ $key }, $some_elementне катит?
Убить всех человеков!
-
diesel
- Бывший модератор
- Сообщения: 5989
- ОС: OS X, openSuSE, ROSA, Debian
Re: Решено: Perl Hash of lists
нет:
Код: Выделить всё
diesel@xenocefal:~$ cat tmp.pl
#!/usr/bin/perl
my %hash = ();
while (<>){
($user, @list) = split /:/, $_;
foreach $item ( @list){
push $hash{$user}, $item;
}
}Код: Выделить всё
diesel@xenocefal:~$ perl -wc tmp.pl
Type of arg 1 to push must be array (not hash element) at tmp.pl line 8, near "$item;"
tmp.pl had compilation errors.а вот так будет работать:
Код: Выделить всё
push @{$hash{$user}}, $item;(просто тестовый пример, ничего лучше в голову не пришло)
Код: Выделить всё
diesel@xenocefal:~$ cat tmp.pl
#!/usr/bin/perl
my %hash = ();
while (<>){
chomp;
($user, @list) = split /:/, $_;
foreach $item ( @list){
push @{$hash{$user}}, $item;
}
}
foreach $item (keys %hash){
print $item . "-> ";
map { print $_ . " "} @{$hash{$item}};
print "\n";
}
diesel@xenocefal:~$ ./tmp.pl /etc/passwd
games-> x 5 60 games /usr/games /bin/sh
...Про сложные структуры данных можно прочитать в perldoc perldsc и perldoc perllol.
-
pcodr
- Сообщения: 283
- ОС: Debian
Re: Решено: Perl Hash of lists
diesel писал(а): ↑13.08.2009 12:15Код: Выделить всё
map { print $_ . " "} @{$hash{$item}}; print "\n";
Хлебом не корми, дай map поюзать
Тот же результат:
Код: Выделить всё
print "@{$hash{$item}}\n";remote system type is unix
-
Lanseg
- Сообщения: 2
- ОС: Arch/OpenSUSE/Gentoo
Re: Решено: Perl Hash of lists
Спасибо
Вопрос закрыт