简体   繁体   English

展平Perl哈希数组

[英]Flatten a Perl array of hashes

Currently have this demonstration code: 当前具有以下演示代码:

use 5.012;
use Data::Dump;

my $AoH = [
    {a => "aval"},  #exactly only one key-value
    {b => "bval"},  #for each
    {c => "cval"},  #array element
];

dd $AoH;

my @arr = map { each $_ } @$AoH;
dd @arr;

it works and produces my wanted result 它起作用并产生我想要的结果

[{ a => "aval" }, { b => "bval" }, { c => "cval" }]
("a", "aval", "b", "bval", "c", "cval")

The question is: is correct the the map { each $_ } construction, or it is possible to do it with "another way"? 问题是: map { each $_ }构造是正确的,还是可以用“另一种方式”完成?

Just dereference the hashrefs: 只需取消引用哈希引用即可:

my $AoH = [
    {a => "aval"},  #exactly only one key-value
    {b => "bval"},  #for each
    {c => "cval"},  #array element
];

# Flatten the hash refs
my @arr = map { %$_ } @$AoH;

I'd advise against using each in that context. 我建议不要在那种情况下使用each From perldoc : 来自perldoc

Starting with Perl 5.14, each can take a scalar EXPR , which must hold reference to an unblessed hash or array. 从Perl 5.14开始, each可以采用标量EXPR ,该标量必须包含对无祝福哈希或数组的引用。 The argument will be dereferenced automatically. 该参数将自动取消引用。 This aspect of each is considered highly experimental. each方面each被认为是高度实验性的。 The exact behaviour may change in a future version of Perl. 确切的行为可能会在Perl的将来版本中更改。

is correct the the map { each $_ } construction, 正确的地图{每个$ _}结构,

Not exactly. 不完全是。 In your specific case, it will do what you want. 在您的特定情况下,它将执行您想要的操作。 However, as pointed out by @ikegami, this will introduce a subtle bug in your code, do what you did twice, you will see the problem. 但是,正如@ikegami指出的那样,这将在您的代码中引入一个细微的错误,重复执行两次,您将看到问题。 Every hash has a internal iterator, and this iterator will be reset only after you exhausted that hash, and read it once more. 每个哈希都有一个内部迭代器,并且只有在用完该哈希并再次读取该哈希之后,才会重置此迭代器。 (It is similar to feof() .) (它类似于feof() 。)

Additionally, each $_ only available since Perl 5.14 or later, for early versions, you need to use map { each %$_ } . 此外, each $_仅从Perl 5.14或更高版本开始可用,对于早期版本,您需要使用map { each %$_ }

However, the REAL problem is that there is no need to use each , you could use map { %$_ } , in list context, hash will return a list made up of its key-value pairs. 但是,真正的问题是,不需要使用each ,可以使用map { %$_ } ,在列表上下文中,hash将返回由其键值对组成的列表。

or it is possible to do it with "another way"? 还是可以用“另一种方式”做到这一点?

Also yes, you could use foreach and push , like this: 同样是的,您可以使用foreachpush ,如下所示:

push @arr, %$_ foreach @$AoH;

However, this is basically the same as your method. 但是,这基本上与您的方法相同。

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

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