我有一个文件,其中每一行都是一个表示id的整数。我想要做的只是检查这个列表中是否有一些特定的ID。 但是代码没有用。它永远不会告诉我它存在,即使123是该文件中的一行。我不知道为什么?帮助赞赏。
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";
}
提前致谢。
答案 0 :(得分:6)
您希望确保正确地创建哈希。过时的chop不是您想要使用的。请改用chomp,并在创建哈希值之前立即在整个阵列上使用它:
open my $fh, '<', 'list.txt' or die "unable to open list.txt: $!";
chomp( my @data = <$fh> );
my $hash = map { $_, 1 } @data;
答案 1 :(得分:2)
答案 2 :(得分:2)
chop
返回它切碎的角色,而不是留下的东西。你可能想要这样的东西:
my %lookup = map { substr($_,0,-1) => undef } @data;
但是,通常情况下,您应该考虑使用chomp
代替chop
来更智能地删除CRLF,因此您最终会得到这样的一行:
my %lookup =map {chomp; $_ => undef } @data;
答案 3 :(得分:2)
你的问题是chop会返回被切断的字符,而不是结果字符串,所以你要创建一个带有换行符的单一条目的哈希。如果您使用Data :: Dumper输出结果哈希,这在调试中很明显。
请改为尝试:
my @data=<FILE>;
chomp @data;
my %lookup = map {$_ => undef} @data;
答案 4 :(得分:2)
使用Perl 5.10及更高版本,您还可以使用智能匹配运算符:
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;
答案 5 :(得分:0)
这应该有效...它使用List :: Util中的first
进行搜索,并删除了初始map
(这假设您不需要存储某些值的值否则紧接着)。 chomp
在搜索值时完成;见perldoc -f chomp。
use List::Util 'first';
open (my $fh, 'list.txt') or die 'unable to open list.txt!';
my @elements = <$fh>;
my $element = '123';
if (first { chomp; $_ eq $element } @elements)
{
print "Exists";
}
答案 6 :(得分:0)
这个可能不完全符合您的具体问题, 但如果你的整数需要 算了,你甚至可以用好 旧的“规范”perl方法:
open my $fh, '<', 'list.txt' or die "unable to open list.txt: $!";
my %lookup;
while( <$fh> ) { chomp; $lookup{$_}++ } # this will count occurences if ints
my $element = '123';
if( exists $lookup{$element} ) {
print "$element $lookup{$element} times there\n"
}
在某些情况下甚至可能比这更快 具有中间阵列的解决方案。
此致
RBO