我正在生成一个哈希并将该哈希推送到一个数组中。最后的数组显示为
$VAR1 = [
{
'Count' => 1,
'maint_wf' => 'WFblabla',
'lines' => {
'line1' => {
'ort' => 'city_x',
'lbz' => 'L1city_x'
}
},
'receive_date' => 'Di, 3 Sep 2013 12:16:43 +0200',
'maint_date' => '02.09.2013',
'calendar' => {
'dtend' => '20130902T0530',
'dtstart' => '20130902T0100'
}
},
{
'Count' => 3,
'maint_wf' => 'WFbla',
'lines' => {
'line3' => {
'ort' => 'city1',
'lbz' => 'L1_city1'
},
'line1' => {
'ort' => 'city2',
'lbz' => 'L1_city2'
},
'line2' => {
'ort' => 'city2',
'lbz' => 'L2_city2'
}
},
'receive_date' => 'Mi, 4 Sep 2013 08:56:35 +0200',
'maint_date' => '03.09.2013',
'calendar' => {
'dtend' => '20130903T0530',
'dtstart' => '20130903T0300'
}
},
...
];
如何计算键'ort'的重复值(即有多少'ort'=>'city2'存在?)然后只显示键'lbz'的相应值?
答案 0 :(得分:1)
my $wanted = "city2";
my @lines;
for my $h (@$arr) {
push @lines, grep { $_->{ort} eq $wanted } values %{$h->{lines}};
}
print "Count:", scalar @lines, "\n";
print $_->{lbz}, "\n" for @lines;
也许更短,但更加模糊,不推荐:
my $wanted = "city2";
printf "Count:%d\n", scalar
map { $_->{ort} eq $wanted ? print "$_->{lbz}\n" : () }
map { values %{$_->{lines}} }
@$arr;
答案 1 :(得分:1)
创建一个计算每个ort值的可能lbz值的哈希可能会对您有所帮助:
#!/usr/bin/perl
use warnings;
use strict;
use Data::Dumper;
my $arrR = [
{
'Count' => 1,
# ...
];
my %ort;
for my $hashR (@$arrR) {
my @lines = values %{ $hashR->{lines} };
for my $line (@lines) {
$ort{ $line->{ort} }{ $line->{lbz} }++;
}
}
print Dumper \%ort;
输出:
$VAR1 = {
'city2' => {
'L1_city2' => 1,
'L2_city2' => 1
},
'city_x' => {
'L1city_x' => 1
},
'city1' => {
'L1_city1' => 1
}
};