【发布时间】:2016-05-06 19:08:38
【问题描述】:
我正在尝试在一个文件中搜索 如果其他文件包含这些数字,则编号并发布
#!/usr/bin/perl
open(file, "textIds.txt"); #
@file = <file>; #file looking into
# close file; #
while(<>){
$temp = $_;
$temp =~ tr/|/\t/; #puts tab between name and id
@arrayTemp = split("\t", $temp);
@found=grep{/$arrayTemp[1]/} <file>;
if (defined $found[0]){
#if (grep{/$arrayTemp[1]/} <file>){
print $_;
}
@found=();
}
print "\n";
close file;
#the input file lines have the format of
#John|7791 154
#Smith|5432 290
#Conor|6590 897
#And in the file the format is
#5432
#7791
#6590
#23140
【问题讨论】:
-
打印出
$arrayTemp[1],你就会知道问题出在哪里了。 -
您已经在脚本的第三行将整个文件内容吞入
@file,但随后您又试图在 grep 语句中从中读取更多行。此时,<file>没有更多内容可以返回给您,并且每次都返回undef。如果你在代码中启用use warnings;,Perl 会告诉你的。 -
@PaulL 您使用
warnings(和strict,即使您没有说出来)的观点是正确的,但是这段代码实际上不会产生任何警告。在这种情况下,我们不知道命令行参数是什么,所以很难说空文件句柄会做什么。但即使是while (<file>)也无济于事;代码根本不会进入循环。 -
Perl script grep的可能重复
-
@MattJacob 你是绝对正确的。我很抱歉。我搞砸了上下文 - 我没有考虑到
grep在<>运算符上强制使用列表上下文。如果它在标量上下文中工作,那么它将返回undef,Perl 肯定会警告不要使用它。尽管如此,(假设只有数字的四行是textIDs.txt的内容,另一个文件在命令行上传递),<file>将简单地返回一个空列表,这 grep 非常高兴在没有警告的情况下使用。谢谢指正。