测试一个字符串是否包含Perl中的哈希键 [英] Test if a string contains the key of a hash in Perl

查看:112
本文介绍了测试一个字符串是否包含Perl中的哈希键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串,并且想知道它是否包含散列键,如果是,我想打印散列值如下所示:

I have a string and want to tell if it contains the key of a hash and if it does I would like to print the value of the hash like so:

#!/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语句中)

Whats the best way to do this? (Preferably concise enough to contain in an if statement)

推荐答案

如果您必须搜索多个字符串,但只有一个不变散列,将散列键编译成正则表达式可能会更快,然后将该正则表达式应用于每个字符串。

If you have to search through multiple strings but have just the one unchanging hash, it might be faster to compile the hash keys into a regexp upfront, and then apply that regexp to each string.

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

这篇关于测试一个字符串是否包含Perl中的哈希键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆