feng63600
feng63600

Reputation: 183

Perl - Using RegExp string as hash keys

Does Perl provide any modules that support using RegExp string as hash keys and allow using a matched string as a key to find value?

For example,

%h = {
  'a.*' : 'case - a',
  'b.*' : 'case - b',
  'c.*' : 'case - c'
}

# expected output
print %h{'app'} # case - a
print %h{'bar'} # case - b
print %h{'car'} # case - c

This example can be handled by an if regex statement, but it will be handy if there is any modules support the functionality.

Upvotes: 0

Views: 965

Answers (1)

Dave Cross
Dave Cross

Reputation: 69244

From the synopsis of Tie::RegexpHash:

use Tie::RegexpHash;

my %hash;

tie %hash, 'Tie::RegexpHash';

$hash{ qr/^5(\s+|-)?gal(\.|lons?)?/i } = '5-GAL';

$hash{'5 gal'};     # returns "5-GAL"
$hash{'5GAL'};      # returns "5-GAL"
$hash{'5  gallon'}; # also returns "5-GAL"

my $rehash = Tie::RegexpHash->new();

$rehash->add( qr/\d+(\.\d+)?/, "contains a number" );
$rehash->add( qr/s$/,          "ends with an \`s\'" );

$rehash->match( "foo 123" );  # returns "contains a number"
$rehash->match( "examples" ); # returns "ends with an `s'"

Which is, I think what you want. Alternatively, my Tie::Hash::Regex uses regexes when looking for hash keys.

use Tie::Hash::Regex;
my %h;

tie %h, 'Tie::Hash::Regex';

$h{key}   = 'value';
$h{key2}  = 'another value';
$h{stuff} = 'something else';

print $h{key};  # prints 'value'
print $h{2};    # prints 'another value'
print $h{'^s'}; # prints 'something else'

print tied(%h)->FETCH(k); # prints 'value' and 'another value'

delete $h{k};   # deletes $h{key} and $h{key2};

Upvotes: 3

Related Questions