0

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.

1
  • 1
    I think that you have the full answer in this post of yesterday. Commented May 9, 2016 at 9:22

1 Answer 1

3

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};
Sign up to request clarification or add additional context in comments.

3 Comments

Is there less expensive options we can go for?
Both modules are open source and freely available from CPAN. It doesn't get any less expensive than that :-)
Oh, I knew what you meant :-) And, no, I can't think of any way of doing this that isn't going to have a horrible effect on performance. Think of what you're asking. You want to invoke the regex engine on every hash look-up. That's never going to be fast.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.