【发布时间】:2016-05-06 22:14:54
【问题描述】:
脚本正在打印输入行的数量,我希望它打印另一个文件中存在的输入行的数量
#!/usr/bin/perl -w
open("file", "text.txt");
@todd = <file>;
close "file";
while(<>){
if( grep( /^$_$/, @todd)){
#if( grep @todd, /^$_$/){
print $_;
}
print "\n";
}
如果例如文件包含
1
3
4
5
7
并且将从中读取的输入文件包含
1
2
3
4
5
6
7
8
9
我希望它打印 1,3,4,5 和 7 但是正在打印 1-9
更新****** 这是我现在的代码,我收到了这个错误 ./may6test.pl 第 3 行关闭文件句柄 todd 上的 readline()。
#!/usr/bin/perl -w
open("todd", "<text.txt");
@files = <todd>; #file looking into
close "todd";
while( my $line = <> ){
chomp $line;
if ( grep( /^$line$/, @files) ) {
print $_;
}
print "\n";
}
这对我来说毫无意义,因为我有另一个脚本基本上在做同样的事情
#!/usr/bin/perl -w
open("file", "<text2.txt"); #
@file = <file>; #file looking into
close "file"; #
while(<>){
$temp = $_;
$temp =~ tr/|/\t/; #puts tab between name and id
my ($name, $number1, $number2) = split("\t", $temp);
if ( grep( /^$number1$/, @file) ) {
print $_;
}
}
print "\n";
【问题讨论】:
-
这与 3 小时前的 this one 几乎相同。如果您是同一个人,我强烈建议不要重复发布来自不同帐户的帖子。否则,我建议您注意已经在 SO 上发布的相同问题。
-
经验法则:避免出于这个原因隐式或显式使用
$_。map和grep是例外,因为需要使用它。