我有以下格式的hashref:
{
introduction_to_systems => {
writer => "John",
owner => "Jim"
},
management_recipies => {
writer => "Jane",
owner => "Jim"
},
etc
}
我遇到的问题是这个哈希不是很方便。我也希望能够轻松找到“Jim”或“John”所拥有的所有作品。
基本上我需要2个这个哈希表的反转 在perl中执行此操作的最有效方法是什么?
答案 0 :(得分:1)
因为每个所有者和作者都可以拥有和编写许多东西,所以你必须使用一系列书籍作为值来制作哈希。你可以通过很多方式做到这一点。例如:
#!/usr/bin/env perl
use strict;
use warnings;
my $books = {
introduction_to_systems => {
writer => "John",
owner => "Jim"
},
management_recipies => {
writer => "Jane",
owner => "Jim"
},
};
my ( %owns, %wrote );
for my $book ( keys %$books ) {
my $rec = $books->{$book};
push @{ $owns{ $rec->{owner} } }, $book;
push @{ $wrote{ $rec->{writer} } }, $book;
}
print "Jim owns @{$owns{Jim}}\n";
print "John wrote @{$wrote{John}}\n";