2

我想动态创建一个结构如下:

{  
   edition1 => {  
                 Jim => ["title1", "title2"],  
                 John => ["title3", "title4"],  
              },  
  edition2 => { 
                 Jim => ["titleX",],  
                 John => ["titleY,],  
              }  etc
}  

我对我是如何做到的感到困惑。
基本上我的想法是:

my $edition = "edition1";  
my $author = "Jim";  
my $title = "title1";  
my %main_hash = ();  

${$main_hash{$edition}} ||= {};   

${$main_hash{$edition}}->{$author} ||= [];     

push @{{$main_hash{$edition}}->{$author}} , $title;   

但不知何故,我不确定如何正确地做到这一点,而且语法似乎很复杂。
我怎样才能以一种很好/清晰的方式实现我想要的?

4

1 回答 1

3

你让自己变得相当困难。Perl 具有自动生存功能,这意味着如果您使用它们,就好像它们包含数据引用一样,它会神奇地为您创建任何必要的哈希或数组元素

你的线

push @{{$main_hash{$edition}}->{$author}} , $title;

是你最接近的,但是你有一对额外的大括号$main_hash{$edition},试图创建一个匿名散列,$main_hash{$edition}并将其作为唯一的键和undef值。您也不需要在右括号和左括号或大括号之间使用间接箭头

这个程序展示了如何使用 Perl 的工具来更简洁地编写这个

use strict;
use warnings;

my %data;

my $edition = "edition1";
my $author  = "Jim";
my $title   = "title1";

push @{ $data{$edition}{$author} }, $title;

use Data::Dump;
dd \%data;

输出

{ edition1 => { Jim => ["title1"] } }
于 2015-08-23T12:54:54.607 回答