如何使用Perl比较两个文件并在第三个文件中打印匹配

时间:2015-02-10 11:14:47

标签: perl

file1.csv
ABC,你好

BAC,男人

CAC,棕褐色

file2.csv
CAV,

盘,

BAC,



Outfile: out文件应该与file2.csv匹配
BAC

2 个答案:

答案 0 :(得分:0)

#!C:\Perl\perl\bin\perl.exe                                  

use strict;
use warnings;

my $file1 = "file1.csv";
my $file2 = "file2.csv";

my @a_file1 = &sub_read ($file1);
my @a_file2 = &sub_read ($file2);

foreach my $entry1 (@a_file1) {
    foreach my $entry2 (@a_file2) {
        if ($entry1 eq $entry2) {
            print "$entry1\n";
        }
    }   
}

sub sub_read {
    my $file = $_[0];
    my @a_file;
    open (READ,"<",$file) or die "$!";
    while (<READ>) {
        chomp ($_);
        my @a_temp = split(/\,/,$_);
        foreach my $a (@a_temp) {
            push (@a_file, $a);
        }
    }
    close (READ);
    return @a_file;
}

我觉得这个很好用。 要打印文件,只需使用以下内容:

open (WRITE, ">> $outfile");
print WRITE "$entry1\n";
close (WRITE);

这有很多可能性(使用哈希)。

答案 1 :(得分:-1)

open( FILE2, "file2.csv" );
open( FILE1, "file1.csv" );

while (<FILE1>) {
    my $element1 = $_;
    push( @file1, $element1 );
}

while (<FILE2>) {

    my $element2 = $_;

    if ( grep( /^$element2$/, @file1 ) ) {
        print "$element1 exists in file1.csv \n";
    }

}