Perl - 使用 RegExp 字符串作为散列键

Perl - Using RegExp string as hash keys

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 语句处理,但如果有任何模块支持该功能,它会很方便。

摘自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};