如何比较perl中的2个csv文件

时间:2017-05-02 12:03:53

标签: perl

我有两个csv文件(A,B)。

档案A

ADDRESSLINKID;NAMEINDEX;ADDRESSLINKINDEX;ADMINREGIONID;TOWNREGIONID;SIDE
1;19;;;1;0
2;21;;;2;0
3;23;;;3;0

文件B

ID;DISPLAYTYPE;URBAN;LINKLENGTH;PARENTID;SOURCEID;TRUCKTOLL
1;19;;;;1;0
2;21;;;;2;0
3;23;;;;3;0

现在我将读出文件B中的字段“SourceID”,其中文件A字段“adresslinkid”存在(读取sourceid,其中adresslinkid eq sourceid)!

sub check_segments {

my $fileA = $dirA."\\lux.adl";
my $fileB = $dirA."\\lux.lin";

open my $fh, '<', $fileA or die "Could not open '$fileA' $!\n";
...

我可以用grep运算符来实现吗???

输出应该是: 结果=(1,2,3,4 ......)

2 个答案:

答案 0 :(得分:1)

我对您的问题或您尝试解决方案的印象不是很深刻,只能打开文件

尽管如此,这是一个可以完成我认为你想要的工作程序

use strict;
use warnings 'all';

use List::Util 'first';

my $file_a = 'fileA.txt';
my $file_b = 'fileB.txt';

my @link_ids   = fetch_file_column($file_a, 'ADDRESSLINKID');
my @source_ids = fetch_file_column($file_b, 'SOURCEID');

my %link_ids = map { $_ => 1} @link_ids;

my @result = grep { $link_ids{$_} } @source_ids;
printf "result = (%s)\n", join ',', @result;


sub fetch_file_column {
    my ($file, $column) = @_;

    open my $fh, '<', $file or die qq{Unable to open "$file" for input: $!};

    my @headers;
    for ( scalar <$fh> ) {
        chomp;
        @headers = split /;/;
    }

    my $idx = first { $headers[$_] eq $column } 0 .. $#headers;
    die qq{Header "$column" not found in "$file"} unless defined $idx;

    map { chomp; ( split /;/ )[$idx];  } <$fh>
}

输出

result = (1,2,3)

答案 1 :(得分:1)

Perl可以使用SQL statements通过DBI对CSV文件执行DBD::CSV

以下示例要求您输入的文件名为file_a.csvfile_b.csv。文件必须位于当前目录中。如果您的文件位于其他位置,请更改f_dir

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

my $dbh = DBI->connect ('dbi:CSV:', '', '',
                        { f_dir => '.',
                          f_ext => ".csv/r",
                          csv_sep_char => ';' })
    || die "$DBI::errstr()";

$dbh->{RaiseError} = 1;

my $result = $dbh->selectall_arrayref ('
select sourceid
from file_a, file_b
where file_a.addresslinkid = file_b.sourceid
');

print 'result = (', join (',', map { @$_ } @$result), ")\n";

在Ubuntu上,这需要以下软件包libdbd-csv-perllibsql-statement-perl

相关问题