Perl - 使用RegExp字符串作为哈希键

时间:2016-05-09 09:19:38

标签: regex perl hashmap key

Perl是否提供支持使用RegExp字符串作为哈希键的任何模块,并允许使用匹配的字符串作为查找值的键?

例如,

%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

此示例可以由if regex语句处理,但如果有任何模块支持该功能,它将会很方便。

1 个答案:

答案 0 :(得分:3)

摘自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'"

哪个,我想你想要什么。或者,我的Tie::Hash::Regex在查找哈希键时使用正则表达式。

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};
相关问题