如何在Perl中编写一个算法,从两个文件中读取数据匹配并打印查询



我在为一个任务编写算法时遇到了困难。我在这里问的每一个问题都让我学到新的东西,谢谢你。

我必须读取一个文本文件(一个表包含一个ID和一个名称),我必须将它们与另一个具有相同ID和名称的文件相匹配。

我想用Perl写一个程序来打印第一个表与第二个表匹配的结果,并且只打印匹配的ID,名称,子ID和日期(第二个表的最后两个字段)。

有谁能帮我一下吗?

我已经试过了。

#!/bin/env perl
use strict;  
use warnings;  
use autodie;  
use Data::Dumper;  
# Create a file handle for the input file 
my $fname = 'secondtable.txt';  
open(my $fh, '<:encoding(UTF-8)', $fname);  
# print header  
my $cname = readline $fh;  
print $cname;  
# # print rows  
while ( my $line = readline $fh ) {
  chomp $line;
  print "$linen";
}
use warnings;
use strict; 
open my $file1, '<', 'in1.txt' or die $!;
open my $file2, '<', 'in2.txt' or die $!;
my %data1;
while(<$file1>){
    chomp;
    next if /^name/;
    my @split = split(/t/);
    $data1{$split[0]}{$split[1]}++;
}
my %data2;
while(<$file2>){
    chomp;
    next if /^name/;
    my @split = split(/t/);
    $data2{$split[0]}{$split[1]}++;
    print "$split[0]t$split[1]n" if $data1{$split[0]}{$split[1]};
}

——

name    id
foo 1
bar 2
baz 3
other   4

——

name    id
bar 1
baz 2
baz 3
other   4

最新更新