简体   繁体   English

比较Perl中的两个文本文件

[英]Compare two text files in Perl

I have several strings in two .txt file. 我在两个.txt文件中有几个字符串。 Both of them contain some similar strings but are not arranged on the same line number. 他们两个都包含一些相似的字符串,但是没有排列在相同的行号上。

For example, file1.txt Carmen Edison Molly Jason Damon Gerard 例如,file1.txt Carmen Edison Molly Jason Damon Gerard

file2.txt Edison Jason file2.txt爱迪生杰森

I want to save the similar strings that found in both text files (in this case: Edison Jason) to an array. 我想将两个文本文件(在本例中为Edison Jason)中找到的相似字符串保存到数组中。

There are various array utility libraries for achieving this - what your after specifically is intersection, Array::Utils being one of the simpler libraries to achieve this; 有各种各样的数组实用程序库可以实现这一目的-您的目标尤其是交集,Array :: Utils是实现此目的的较简单的库之一;

#!/usr/bin/env perl
use strict;
use warnings;

use File::Slurp qw(read_file);
use Array::Utils qw(intersect);

my $file1 = 'file1.txt';
my $file2 = 'file2.txt';

my @data1 = split( /\s/, read_file($file1) );
my @data2 = split( /\s/, read_file($file2) );

my @intersect = intersect( @data1, @data2 );

print join(', ', @intersect), "\n";

Or, without requiring Array::Utils 或者,不需要Array :: Utils

#!/usr/bin/env perl
use strict;
use warnings;

my @data1 = qw( Carmen Edison Molly Jason Damon Gerard );
my @data2 = qw( Edison Jason );

sub intersect {
  my %e = map { $_ => undef } @{$_[0]};
  return grep { exists( $e{$_} ) } @{$_[1]};
}

my @intersect = intersect( \@data1, \@data2 );
print join(', ', @intersect), "\n";

Without the need to use additional modules 无需使用其他模块

#!/usr/bin/env perl
use strict;
use warnings;

my @data1 = qw( Carmen Edison Molly Jason Damon Gerard );
my @data2 = qw( Edison Jason );
my @data3 = ();

foreach my $d1 ( @data1 )
{
    chomp $d1;

    foreach my $d2 ( @data2 )
    {
        chomp $d2;

        if( $d1 eq $d2 )
        {
            print "Match Found : $d1, $d2 \n";
            push @data3, $d1;
        }
    }
}

you could do it this way without installing any additional modules 您可以通过这种方式进行操作而无需安装任何其他模块

#!/usr/bin/perl
use warnings;
use strict;

my (@file1,@file2,@match);

open FILE1, "<", 'file1.txt';
@file1 = <FILE1>;
close FILE1;

open FILE2, "<", 'file2.txt';
@file2 = <FILE2>;
close FILE2;

chomp (@file1,@file2);

foreach(@file1) {
    if ($_ ~~ @file2) {
        push @match, $_;
    }
}

print "\nMatches\n";
foreach(@match) { print "The same -- $_\n"; }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM