我试图在一个文件中搜索该实例 如果另一个文件包含这些数字,则编号和发布
#!/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
答案 0 :(得分:3)
您的脚本中存在一些问题。
use strict;
和use warnings;
。
这会提前告诉你脚本中的奇怪事情。open( my $fh, '<', 'testIds.txt');
use autodie;
或检查开幕是否有效。testIds.txt
存储到数组@file
中,但稍后(在您的grep
中)
再次尝试从该文件(句柄)读取(使用<file>
)。正如@PaulL所说,这将永远
给undef
(false),因为文件已被读取。|
然后在制表符处拆分不是必需的。你可以拆分
选项卡和管道同时(假设&#34; John | 7791 154&#34; 真的&#34; John | 7791 \ t154&#34;)。|
&#39;)。考虑到这一点,您的脚本可以写成:
#!/usr/bin/perl
use strict;
use warnings;
# Open 'textIds.txt' and slurp it into the array @file:
open( my $fh, '<', 'textIds.txt') or die "cannot open file: $!\n";
my @file = <$fh>;
close($fh);
# iterate over STDIN and compare with lines from 'textIds.txt':
while( my $line = <>) {
# split "John|7791\t154" into ("John", "7791", "154"):
my ($name, $number1, $number2) = split(/\||\t/, $line);
# compare $number1 to each member of @file and print if found:
if ( grep( /$number1/, @file) ) {
print $line;
}
}