匹配散列中的键以返回perl中的相应键+值

时间:2016-12-04 12:16:34

标签: regex perl hash

我有一个哈希。我希望通过匹配键的字符串模式来获取键和值。

例如,我有像这样的哈希

 my %hash =  { FIELDN1 = > "N1", FIELDN2 => "N2", FIELDM1 => "M1", FILEDM2 =>"M2"}

我希望得到密钥,并且密钥中的值为1,如下所示。

{ FIELDN1 = > "N1", FIELDM1 => "M1" }

2 个答案:

答案 0 :(得分:3)

如果您需要相应值满足要求的密钥,最好分开保存:

$converted = [
    "NOT LIKE '%red%' AND NOT LIKE '%black%' AND NOT LIKE '%purple%' AND NOT LIKE '%orange%'",
    "LIKE '%red%' AND NOT LIKE '%black%' AND NOT LIKE '%purple%' AND NOT LIKE '%orange%'",
    "LIKE '%black%' AND NOT LIKE '%purple%' AND NOT LIKE '%orange%' AND NOT LIKE '%red%'",
    "LIKE '%purple%' AND NOT LIKE '%orange%' AND NOT LIKE '%red%' AND NOT LIKE '%black%'",
    "LIKE '%orange%' AND NOT LIKE '%red%' AND NOT LIKE '%black%' AND NOT LIKE '%purple%'",
];

如果您还想从#!/usr/bin/env perl use strict; use warnings; my %hash = ( FIELDN1 => "N1", FIELDN2 => "N2", FIELDM1 => "M1", FILEDM2 => "M2", ); my @subset_keys = grep /1\z/, keys %hash; my %subset; @subset{ @subset_keys } = @hash{ @subset_keys }; # contrived example for needing the matching keys for my $k ( @subset_keys ) { print "$k = $subset{$k}\n"; } 中删除匹配的密钥,请使用:

%hash

或者,如果您只想从@subset{ @subset_keys } = delete @hash{ @subset_keys }; 中删除不匹配的条目:

%hash

delete @hash{ grep !/1\z/, keys %hash }; 现在将包含:

---
FIELDM1: M1
FIELDN1: N1

答案 1 :(得分:2)

这将按照您的要求进行

use strict;
use warnings 'all';

my %hash = ( FIELDN1 => "N1", FIELDN2 => "N2", FIELDM1 => "M1", FILEDM2 => "M2" );

my %subset = map { $_ => $hash{$_} } grep { /1$/ } keys %hash;

use Data::Dumper;
print Dumper \%subset;

输出

$VAR1 = {
          'FIELDN1' => 'N1',
          'FIELDM1' => 'M1'
        };