需要帮助找出工作的perl代码来代替"@array中的任何元素"
%hash = (key1 => 'value1',key2 => 'value2',key3 => 'value3',);
@array= ('value3','value4','value6');
if ($hash{ 'key1' } ne <<any of the elements in @array>>) {print "YAY!";}
Run Code Online (Sandbox Code Playgroud)
CPAN解决方案:使用 List::MoreUtils
use List::MoreUtils qw{any};
print "YAY!" if any { $hash{'key1'} eq $_ } @array;
Run Code Online (Sandbox Code Playgroud)
为什么使用这个解决方案而不是替
在5.10之前不能在Perl中使用智能匹配
grep即使1,000,000个长列表的第一个元素匹配,解决方案也会遍历整个列表.any将在发现第一场比赛时短路并退出,因此效率更高.