简体   繁体   English

如何从哈希哈希中获取哈希切片?

[英]How do I get a hash slice from a hash of hashes?

I have a hash like so: 我有这样的哈希:

my %h = ( a => { one => 1,
                 two => 2
             },
          b => { three => 3,
                 four => 4
             },
          c => { five => 5,
                 six => 6
             }
      );

print join(',', @{$h{a}{qw/one two/}});

The error I get is: Can't use an undefined value as an ARRAY reference at q.pl line 17 which is the line with the print. 我得到的错误是:不能使用未定义的值作为q.pl第17行的ARRAY引用,这是打印行。

What I expected is 1,2 我的预期是1,2

To get a hash slice from a nested hash, you have to de-reference it in steps. 要从嵌套哈希中获取哈希切片,您必须逐步取消引用它。 You get the first level that you need: 你得到了你需要的第一级:

$h{'a'}

Now, you have to dereference that as a hash. 现在,你必须取消引用它作为哈希。 However, since it's not a simple scalar, you have to put it in braces. 但是,由于它不是一个简单的标量,你必须把它放在括号中。 To get the whole hash, you'd put a % in front of the braces: 要获得整个哈希值,您需要在大括号前加一个%

%{ $h{'a'} }

Now you want a slice, so you replace the % with an @ , since you're getting multiple elements, and you also put your keys at the end as normal: 现在你想要一个切片,所以你用@替换% ,因为你得到了多个元素,并且你也正常地将你的键放在最后:

@{ $h{'a'} }{ @keys }

It might look easier to see the braces separately: 分别看到大括号可能更容易:

@{         }{       }
   $h{'a'}    @keys

To make this simpler, v5.20 introduced the postfix dereference . 为了简化这一点,v5.20引入了后缀解除引用 Instead of wrapping thing in braces and working from the inside out, you can work from left to right: 您可以从左到右工作,而不是将东西包在支架中并从内到外工作:

$h{a}->@{qw/one two/};

That @ is the same thing you saw in front of the first brace. 那个@就像你在第一个支架前看到的一样。 You still know it's a hash slice because a brace follows the sigil. 你仍然知道它是一个哈希切片,因为支撑跟随着这个印记。

try 尝试

print join(',',@{$h{'a'}}{qw/one two/});

use of Data::Dumper greatly helps in cases like this one Data :: Dumper的使用极大地有助于像这样的情况

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM