Gigil K G
Gigil K G

Reputation: 13

Match keys in a hash to return respective key+value in perl

I have a hash. I want to get key and values by matching string pattern of keys.

For example, I have a Hash like this

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

I want to get key and value having 1 in the keys as given below.

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

Upvotes: 1

Views: 1230

Answers (2)

Sinan Ünür
Sinan Ünür

Reputation: 118128

If you are going to need the keys whose corresponding values satisfy the requirement, you might be better off saving them separately:

#!/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";
}

If you also want to remove the matching keys from %hash, use:

@subset{ @subset_keys } = delete @hash{ @subset_keys };

Or, if you just want to remove the non-matching entries from %hash:

delete @hash{ grep !/1\z/, keys %hash };

%hash will now contain:

---
FIELDM1: M1
FIELDN1: N1

Upvotes: 3

Borodin
Borodin

Reputation: 126722

This will do as you ask

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;

output

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

Upvotes: 2

Related Questions