regex - Perl - Using RegExp string as hash keys -


does perl provide modules support using regexp string hash keys , allow using matched string key find value?

for example,

%h = {   'a.*' : 'case - a',   'b.*' : 'case - b',   'c.*' : 'case - c' }  # expected output print %h{'app'} # case - print %h{'bar'} # case - b print %h{'car'} # case - c 

this example can handled if regex statement, handy if there modules support functionality.

from synopsis of tie::regexphash:

use tie::regexphash;  %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'}; # returns "5-gal"  $rehash = tie::regexphash->new();  $rehash->add( qr/\d+(\.\d+)?/, "contains number" ); $rehash->add( qr/s$/,          "ends \`s\'" );  $rehash->match( "foo 123" );  # returns "contains number" $rehash->match( "examples" ); # returns "ends `s'" 

which is, think want. alternatively, tie::hash::regex uses regexes when looking hash keys.

use tie::hash::regex; %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' , 'another value'  delete $h{k};   # deletes $h{key} , $h{key2}; 

Comments

Popular posts from this blog

javascript - Laravel datatable invalid JSON response -

java - Exception in thread "main" org.springframework.context.ApplicationContextException: Unable to start embedded container; -

sql server 2008 - My Sql Code Get An Error Of Msg 245, Level 16, State 1, Line 1 Conversion failed when converting the varchar value '8:45 AM' to data type int -