perl - 我如何检查一个值是否在 Perl 的列表中?

我有一个文件,其中每一行都是一个代表一个 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";
    }

提前致谢。

最佳答案

你想确保你的哈希值是正确的。非常过时的chop不是你想用的。使用 chomp相反,在创建散列之前立即在整个数组上使用它:

 open my $fh, '<', 'list.txt' or die "unable to open list.txt: $!";
 chomp( my @data = <$fh> );
 my $hash = map { $_, 1 } @data;

https://stackoverflow.com/questions/2678503/

相关文章:

objective-c - 将 IOKit IOReturn 错误代码映射到字符串

xml - 对齐 ="right"在 XML 中不起作用

sql-server - 在数据库中存储 & 符号

shell - 在 unix shell 脚本中用空格替换换行符

sql-server - UPDATE 表中除 TOP 1 记录外的记录

php - preg_replace : how do I strip off all white

python - python中的文本压缩

sql - 如何从 SQL Server 数据库可视化 nvarchar(max) 的值,其中 ma

c# - 通过鼠标移动控件

php - eval {php} 条件