![](/img/trans.png)
[英]Sorting an array of hashes, based on the value of a particular key within each hash in perl
[英]Search in an array of hashes by the hash key and its sorting in Perl
我有大约 300 个 hash 项的哈希数组:
@whole = [
{
'id' => 112,
'name' => 'Wheelbase',
'lang' => 'en'
},
{
'lang' => 'en',
'name' => 'Width',
'id' => 57
},
{
'lang' => 'en',
'id' => 174,
'name' => 'WLAN'
},
{
'id' => 252,
'name' => 'Zoom System',
'lang' => 'en'
};
];
我想在上述数据结构中搜索多个键名,并将多个名称存储在另一个数组中。
@props = ('Price', 'Market Dominance', 'Market Capitalization');
我的代码是:
use strict;
use warnings;
my (@matching_items, @whole); # input arrays both
my $id_prop;
@matching_items = grep {
foreach my $in (@props) {
if ($_->{name} =~ /^$in$/i) {
$id_prop = $_->{id};
print "$id_prop\n";
}
}
} @whole;
print Dumper @matching_items;
这不会填充@matching_items 中的匹配项。 它返回为空并仅将 id 打印到控制台。 我做错了什么?
您正在为@whole
分配一个引用文字,我将其更改为一个数组。 使用List::Util::any
可以更轻松地编写嵌套的foreach
,这将在使块评估为 true 的第一个元素上使用快捷方式。 我还在循环之前将您的@props
条目小写一次,并使用eq
与小写的名称字符串进行比较:
use strict;
use warnings;
use List::Util qw/any/;
use Data::Dumper;
use 5.016;
my @whole = (
{
'id' => 112,
'name' => 'Wheelbase',
'lang' => 'en'
},
{
'lang' => 'en',
'name' => 'Width',
'id' => 57
},
{
'lang' => 'en',
'id' => 174,
'name' => 'WLAN'
},
{
'id' => 252,
'name' => 'Zoom System',
'lang' => 'en'
}
);
my @props = ('Price', 'Market Dominance', 'Market Capitalization','Zoom System');
my @props_lc = map {lc} @props;
my @matching_items = grep {
my $name = lc $_->{name};
any {$name eq $_} @props_lc;
} @whole;
print Dumper @matching_items;
这是另一种方法:
my @whole = (
{
'id' => 112,
'name' => 'Wheelbase',
'lang' => 'en'
},
{
'lang' => 'en',
'name' => 'Width',
'id' => 57
},
);
my %props = map {$_ => 1} ('Width', 'Market Dominance', 'Market Capitalization');
my @matching_items = grep { exists $props{$_->{name}} } @whole;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.