ajwood
ajwood

Reputation: 19027

Perl: Matching hash keys to a regular expression

I'm wondering if Perl has a built-in way to check for the existence of a hash element with a key matching a particular regex. For example:

my %h = ( 'twelve' => 12, 'thirteen' => 13, 'fourteen' => 14 );

I'm wondering if there is any way to do this:

print "We have 12\n" if exists $h{twelve};
print "We have some teens\n" if exists $h{/.*teen$/};

Upvotes: 18

Views: 36673

Answers (4)

Axeman
Axeman

Reputation: 29854

Yeah, it's called:

use List::Util qw<first>;

# Your regex does not compile perhaps you mean /teen$/
my $value = $hash{ ( first { m/teen/ } keys %hash ) || '' };

(Before smart match, that is. See mob's answer for smart match.)

You could also sort the keys:

my $value = $hash{ ( first { m/teen/ } sort keys %hash ) || '' };

I would freeze this into an "operation":

use Scalar::Util qw<reftype>;

sub values_for_keys_like (\[%$]$) {
    my $ref = reftype( $_[0] ) eq 'HASH' ? $_[0] : $$_[0];
    return unless my @keys = keys %$ref;

    my $regex = shift;
    # allow strings
    $regex    = qr/$regex/ unless my $typ = ref( $regex );
    # allow regex or just plain ol' filter functions.
    my $test  = $typ eq 'CODE' ? $regex : sub { return unless m/$regex/; 1 };

    if ( wantarray ) { 
        return unless my @k = grep { defined $test->( $_ ) } @keys;
        return @$ref{ @k };
    }
    else {
        return unless my $key = first { defined $test->( $_ ) } @keys;
        return $ref->{ $key };
    }
}

And you could use it like so:

my $key = values_for_keys_like( %hash => qr/teen/ );

Or

my $key = values_for_keys_like( $base->{level_two}{level_three} => qr/teen/ );

Upvotes: 6

In addition to the other answers here you can also do this with perl's grep:

print "We have some teens\n" if grep {/.*teen/} keys %h;

Upvotes: 12

mob
mob

Reputation: 118605

The smart match operator does this (available since Perl v5.10).

$a      $b        Type of Match Implied    Matching Code
======  =====     =====================    =============
...
Regex   Hash      hash key grep            grep /$a/, keys %$b
...

Sample usage:

# print if any key in %h ends in "teen"
print "We have some teens\n" if /.*teen$/ ~~ %h;

Upvotes: 25

Eugene Yarmash
Eugene Yarmash

Reputation: 149756

There's no built-in way, but there's Tie::Hash::Regex on CPAN.

Upvotes: 4

Related Questions