regexperlperl-hash

Check if pattern exists in a keys of hash


I have a hash of following pattern

my %hash_table(
     23                => someintegertype,
     type              => somestringtype,
     12_someidentifier => someveryproblematictype
);

How do I check if pattern that 12_someidentifier key follows exists in the hash or not? If so, I need to know the value in the form of true or false.

::UPDATE:: I wanted to check if the regex or pattern such as {[\d]_[\w+]} exists or not?


Solution

  • exists tells you if a key exists. $hash{$key} gives you the value, so you can test it.

    If you're looking to test multiple values against a regex (such as they keys of a hash) then the tool for the job is grep;

    my @matches = grep { /\d+_\w+/ } keys %hash_table;
    print @matches;
    

    Whilst we're at it - turn on use strict; and use warnings;. It'll help in the long run.