如何比较perl中的两个文本

时间:2015-04-02 03:17:17

标签: perl

我有2个文件:
1. a.txt
2. b.txt

A.TXT:

UP_00292229  191
Xa_09833888  199

b.txt

UP_00292229  191
Xa_09833888  188

我想将这两个文件与第一列进行比较。

结果:

UP_00292229 is same
Xa_09833888 is not same

我怎样才能在perl中做到? 如何同时输入2个文件?
如何检查文件格式是xxxxx dddd(xxxxx dddd之间有空格)?

2 个答案:

答案 0 :(得分:0)

试试这个:

use warnings;
use strict;

open my $handle_file1,"<","file1";
open my $handle_file2,"<","file2";

my @ar = <$handle_file1>;
my @br = <$handle_file2>;

for my $i(0..$#ar){

    if($ar[$i] eq $br[$i]){
        chomp $ar[$i];
        print "$ar[$i] is same\n";
    }
    else{
        chomp $ar[$i];
        print "$ar[$i] is not same\n";
    }
}

答案 1 :(得分:0)

此代码将比较两个文件的first column,如果值匹配则会打印same,否则not same

use strict;
use warnings;

my %seen;
open ( my $file2,"<", "b.txt" ) or die $!;
while ( my $line = <$file2> )
{
   chomp ( $line );
   my ($column3, $column4) = split ' ', $line;
   $seen{$column3}++;
}
close ( $file2 );

open ( my $file1, "<", "a.txt" ) or die $!; 
while ( my $line1 = <$file1> )
{
   chomp $line1;
   my ($column1, $column2) = split ' ', $line1;
   print $column1, " ", $seen{$column1} ? "is same" : "is not same", "\n";
}
close ( $file1 );
相关问题