如何检查,如果值是在Perl列表? [英] How can I check if a value is in a list in Perl?
本文介绍了如何检查,如果值是在Perl列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个文件,其中的每一行是一个整数,再presents的ID。我想要做的就是检查一些特定的ID是否在此列表中。
但是,code没有工作。它从来没有告诉我它的存在,即使123在该文件中的一行。我不知道为什么?帮助AP preciated。
I have a file in which every line is an integer which represents an id. What I want to do is just check whether some specific ids are in this list. But the code didn't work. It never tells me it exists even if 123 is a line in that file. I don't know why? Help appreciated.
open (FILE, "list.txt") or die ("unable to open !");
my @data=<FILE>;
my %lookup =map {chop($_) => undef} @data;
my $element= '123';
if (exists $lookup{$element})
{
print "Exists";
}
先谢谢了。
推荐答案
用Perl 5.10及以上,您还可以使用智能匹配运算符:
With Perl 5.10 and up, you can also use the smart match operator:
my $id = get_id_to_check_for();
open my $fh, '<', 'list.txt' or die "unable to open list.txt: $!";
chomp( my @data = <$fh> );
print "Id found!" if $id ~~ @data;
这篇关于如何检查,如果值是在Perl列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文