【问题标题】:Dynamically create hash of hash with array ref values使用数组 ref 值动态创建散列的散列
【发布时间】:2015-11-16 22:05:38
【问题描述】:

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

{  
   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;   

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

【问题讨论】:

  • 这个结构背后的目的是什么?它看起来像是一种奇怪的形状,就好像你正试图用它做其他事情,比如创建 JSON。

标签: perl hash hashtable hashref arrayref


【解决方案1】:

你让自己变得相当困难。 Perl 有 autovivication 这意味着如果你像使用它们包含数据引用一样使用它们,它会神奇地为你创建任何必要的散列或数组元素

你的线路

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

【讨论】:

  • 我在一个循环中创建它。所以基本上我不应该关心初始化一个空数组或空hashref?
  • 使用Data::Dump显示数据结构内容的命令。它类似于Data::Dumper 和Dumper。
  • @Jim:正确。 Perl 会根据需要为您设置匿名数据结构。 dd 是Data::Dump 导出的子程序,用来很好的显示你传递给它的数据
  • “我在循环中创建这个” 我也这么想。你的问题给我的工作很少,而且承认它的缺点已经很晚了。我希望你能从这次经历中获得,更好地表达你的问题,而不是依赖可能阅读它的人的分析能力
猜你喜欢
  • 2016-07-02
  • 1970-01-01
  • 1970-01-01
  • 2014-05-19
  • 1970-01-01
  • 1970-01-01
  • 2013-08-11
  • 1970-01-01
  • 2012-06-12
相关资源
最近更新 更多