3

My hash looks like this :

$VAR1 = {
      '1238' => {
                  'OUT3FA_5' => 65,
                  'SEV' => '3_major',
                  'OUT3A_5' => 20,
                  'OUT3-Fix' => 45,
                  'IN1' => 85
                },
      '1226' => {
                  'OUT3FA_5' => 30,
                  'SEV' => '4_minor',
                  'OUT3A_5' => 5,
                  'OUT3-Fix' => 25,
                  'IN1' => 40
                },
      '1239' => {
                  'OUT3FA_5' => 56,
                  'SEV' => '4_minor',
                  'OUT3A_5' => 34,
                  'OUT3-Fix' => 22,
                  'IN1' => 94
                }]

I want my Perl script to only return the values corresponding to "SEV" = "4_minor" In this case it'll return :

    '1226' => {
                  'OUT3FA_5' => 30,
                  'SEV' => '4_minor',
                  'OUT3A_5' => 5,
                  'OUT3-Fix' => 25,
                  'IN1' => 40
                },
      '1239' => {
                  'OUT3FA_5' => 56,
                  'SEV' => '4_minor',
                  'OUT3A_5' => 34,
                  'OUT3-Fix' => 22,
                  'IN1' => 94
                }

But when I use grep like this :

my $Sev_Logged = "4_minor";
my $node_hash = {
Week => [
  grep {  $hash{$_}{'SEV'} eq $Sev_Logged } %hash,
   ]
    };

# Print in json format
my $json = encode_json \%$node_hash;
print $json;

It only returns :

{"Week":["1226","1239"]}

And I want it to return all the other data corresponding to each of the weeks found containing SEV="4_minor". How can I do this? Any help would be much appreciated.

4

1 回答 1

9

当您将%hash这种方式移交给Perl 时, grepPerl 会将散列解释为键和值的偶数列表 - 导致grep {...}每个键调用一次块,每个值调用一次(而不是为每一对调用核心价值)。

尝试这样的事情:

{ map { ($_ => $hash{$_} } grep { $hash{$_}->{SEV} eq $Sev_Logged } keys %hash }

grep保留那些SEV字段与您想要的匹配的哈希键。map之后重建一个哈希(因为那时我们只有从 返回的键)grep,最后我们将它转​​换为一个哈希引用。

于 2012-11-21T15:49:14.603 回答