简体   繁体   English

Perl:切片哈希

[英]Perl: slicing an array of hashes

The output of the code below is always empty. 以下代码的输出始终为空。 Not sure what I am doing wrong and would appreciate any help. 不知道我在做什么错,将不胜感激。 How do I get to the values of a key in a specific hash in an array of hashes? 如何获得哈希数组中特定哈希中的键值?

use strict;
use warnings;

my %dot1 = ('a'=>1,'b'=>2);
my %dot2 = ('a'=>3,'b'=>4);
my %dot3 = ('a'=>5,'b'=>6);
my %dot4 = ('a'=>7,'b'=>8);

my @array = (%dot1,%dot2,%dot3,%dot4);

my %x = $array[2];
my $y = $x->{'a'};

print "$y \n";

You don't have an array of hashes . 您没有一系列哈希 You have an array that looks like a hash, where the keys a and b will be there four times each, in relatively random order. 您有一个看起来像哈希的数组,其中键ab将以相对随机的顺序分别出现四次。

print Dumper \@array;
$VAR1 = [
          'a',
          1,
          'b',
          2,
          'a',
          3,
          'b',
          4,
          'a',
          5,
          'b',
          6,
          'a',
          7,
          'b',
          8
        ];

Afterwards, you are using $x->{a} , which is the syntax to take the key a from the hashref $x , but you only ever declared a hash %a . 之后,您将使用$x->{a} ,这是从hashref $x获取键a的语法,但您只声明了哈希%a That in turn breaks, because you give it an odd-sized list of one value. 这反过来会中断,因为您给它一个奇数大小的一个值列表。

Instead, add references to the hashes to your array. 而是将对哈希的引用添加到数组中。 That way you will get a multi-level data structure instead of a flat list. 这样,您将获得一个多级数据结构而不是一个平面列表。 Then make the x variable a scalar $x . 然后将x变量设为标量$x

my %dot1 = ('a'=>1,'b'=>2);
my %dot2 = ('a'=>3,'b'=>4);
my %dot3 = ('a'=>5,'b'=>6);
my %dot4 = ('a'=>7,'b'=>8);

my @array = (\%dot1,\%dot2,\%dot3,\%dot4); # here


my $x = $array[2]; # here
my $y = $x->{'a'};

print "$y \n";

This will print 5 . 这将打印5

You should read up on data structures in perlref and perlreftut . 您应该阅读perlrefperlreftut中的数据结构。

If you want an array of hash references, you need to say so explicitly. 如果要使用散列引用数组,则需要明确声明。

my @array = (\%dot1, \%dot2, \%dot3, \%dot4);
my %x = %{$array[2]};
my $y = $x{a};
print "$y\n";

What you want to do is add references to your hashes to your @array , otherwise perl will evaluate the hashes in list context. 您要做的是将对哈希的引用添加到@array ,否则perl将在列表上下文中评估哈希。

my @array = (\%dot1,\%dot2,\%dot3,\%dot4);
my $x = $array[2];
my $y = $x->{'a'};

print "$y \n";

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

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