使用 perl 比较文件中的行
我一直在尝试比较两个文件之间的行以及相同的匹配行。
由于某种原因,下面的代码只遍历“text1.txt”的第一行并打印“if”语句,无论两个变量是否匹配。
谢谢
use strict;
open( <FILE1>, "<text1.txt" );
open( <FILE2>, "<text2.txt" );
foreach my $first_file (<FILE1>) {
foreach my $second_file (<FILE2>) {
if ( $second_file == $first_file ) {
print "Got a match - $second_file + $first_file";
}
}
}
close(FILE1);
close(FILE2);
Ive been trying to compare lines between two files and matching lines that are the same.
For some reason the code below only ever goes through the first line of 'text1.txt' and prints the 'if' statement regardless of if the two variables match or not.
Thanks
use strict;
open( <FILE1>, "<text1.txt" );
open( <FILE2>, "<text2.txt" );
foreach my $first_file (<FILE1>) {
foreach my $second_file (<FILE2>) {
if ( $second_file == $first_file ) {
print "Got a match - $second_file + $first_file";
}
}
}
close(FILE1);
close(FILE2);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
如果比较字符串,请使用 eq 运算符。
"=="
以数字方式比较参数。If you compare strings, use the
eq
operator."=="
compares arguments numerically.如果您的文件不太大,这里有一种方法可以完成这项工作。
Here is a way to do the job if your files aren't too large.
一种更好更快(但内存效率较低)的方法是将一个文件读入散列,然后在散列表中搜索行。这样您只需检查每个文件一次。
A better and faster (but less memory efficient) approach would be to read one file into a hash, and then search for lines in the hash table. This way you go over each file only once.
您必须重新打开或重置文件 2 的指针。将
open
和close
命令移至循环内。根据文件和行的大小,更有效的方法是仅循环一次文件并将文件 1 中出现的每一行保存在哈希中。然后检查文件 2 中的每一行是否存在该行。
You must re-open or reset the pointer of file 2. Move the
open
andclose
commands to within the loop.A more efficient way of doing this, depending on file and line sizes, would be to only loop through the files once and save each line that occurs in file 1 in a hash. Then check if the line was there for each line in file 2.
如果你想要行数,
如果你想要匹配的行,
如果你想要不匹配的行,
If you want the number of lines,
If you want the matching lines,
If you want the lines which do not match,
这是我编写的一个脚本,尝试查看两个文件是否相同,尽管可以通过使用代码并将其切换到 eq 来轻松修改它。正如 Tim 建议的那样,使用哈希可能会更有效,尽管您无法确保在不使用 CPAN 模块的情况下按照文件插入的顺序对文件进行比较(正如您所看到的,此方法实际上应该使用两个循环,但这对于我的目的来说已经足够了)。这并不是有史以来最伟大的脚本,但它可能会给您一个起点。
This is a script I wrote that tries to see if two file are identical, although it could easily by modified by playing with the code and switching it to eq. As Tim suggested, using a hash would probably be more effective, although you couldn't ensure the files were being compared in the order they were inserted without using a CPAN module (and as you can see, this method should really use two loops, but it was sufficient for my purposes). This isn't exactly the greatest script ever, but it may give you somewhere to start.
将您发布的代码转换为实际的 Perl 代码,这就是我的想法。
现在您可能真正想要的是两个文件的差异,最好留给 Text: :差异。
Taking the code you posted, and transforming it into actual Perl code, this is what I came up with.
Now what you may really want is a diff of the two files, which is best left to Text::Diff.