测试字符串是否包含Perl中哈希的键

时间:2014-10-02 00:52:01

标签: regex string perl hashmap

我有一个字符串,想知道它是否包含哈希的密钥,如果确实如此,我想像这样打印哈希值:

#!/usr/bin/perl -w

my %h = ( 'key1' => 'v1', 'key2' => 'v2', 'key3' => 'v3' );
my $str = "this is a string containing key1\n";
if ($str contains a key of %h){
    print the value of that key; #i.e v1
}

这是最好的方法吗? (最好简明扼要地包含在if语句中)

3 个答案:

答案 0 :(得分:5)

#!/bin/perl -w

my %h = ( 'key1' => 'v1', 'key2' => 'v2', 'key3' => 'v3' );
my $str = "this is a string containing key1\n";
while (($key, $value) = each %h) {
  if (-1 != index($str, $key)) {
    print "$value\n";
  }
}

答案 1 :(得分:3)

如果你必须搜索多个字符串但只有一个不变的哈希值,那么将哈希密钥编译到正则表达式中可能会更快,然后将该正则表达式应用于每个字符串。

my %h = ( 'key1' => 'v1', 'key2' => 'v2', 'key3' => 'v3' );
my $hash_keys = qr/${\ join('|', map quotemeta, keys %h) }/;

my @strings = (
   "this is a string containing key1\n",
   "another string containing key1\n",
   "this is a string containing key2\n",
   "but this does not\n",
);

foreach my $str (@strings) {
   print "$str\n" if $str =~ $hash_keys;
}

答案 2 :(得分:1)

在某些情况下(大哈希,键是单词而你不希望它们与子词匹配)这可能是正确的方法:

my %h = ( 'key1' => 'v1', 'key2' => 'v2', 'key3' => 'v3' );
my $str = "this is a string containing key1 and key3 but notkey2, at least not alone\n";

while ($str =~ /(\w+)/g) {
    my $v = $h{$1};
    print "$v\n" if defined $v;
}