如何写一个算法在Perl读取两个文件的匹配数据,并打印查询 [英] How to write an algorithm in Perl to read data from two files match and print the query

查看:732
本文介绍了如何写一个算法在Perl读取两个文件的匹配数据,并打印查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在困难的情况下写一个算法的任务。我问这里的每一个问题,我学​​习了新的东西和感谢。

我要读一个文本文件(一个表包含ID和姓名),我不得不与具有相同的ID和名称的另一个文件与之匹配。

我想要写在Perl程序打印出来的结果是将匹配第一个表与第二,并打印匹配的ID,姓名,子ID和日期(最后两个从第二个表中的字段)。

谁能帮我这个?

这是我已经试过了。

 #!/ bin中/ perl的包膜

使用严格的;
使用警告;
使用autodie;

使用数据::自卸车;

#输入文件创建一个文件句柄
我的$ FNAME ='secondtable.txt';
开放式(我$跳频,'<:编码(UTF-8)',$ FNAME);

#打印头
我的$的cname = readline的$跳频;
打印$ CNAME;

##打印行
而(我的$行= $的ReadLine FH){
  终日啃食$线;
  打印$行\ N的;
}
 

解决方案

 使用警告;
使用严格的;

打开我的$文件1,'<','in1.txt或死亡$!;
打开我的$文件2,<','in2.txt或死亡$!;

我的%DATA1;
而(小于$文件1>){
    终日啃食;
    接下来,如果/ ^名称/;
    我@split =拆分(/ \ T /);
    $数据1 {$分割[0]} {$分割[1]} ++;
}

我的%DATA2;
而(小于$文件2&GT){
    终日啃食;
    接下来,如果/ ^名称/;
    我@split =拆分(/ \ T /);
    $数据2 {$分割[0]} {$分割[1]} ++;
    打印$分割[0] \ T $分割[1] \ N如果$数据1 {$分割[0]} {$分割[1]};
}
 

--- IN1 ---

 名ID
FOO 1
酒吧2
巴兹3
其他4
 

--- IN2 ---

 名ID
酒吧1
巴兹2
巴兹3
其他4
 

I am in a difficult situation writing an algorithm for a task. Every question I ask here I am learning something new and thanks for that.

I have to read a text file (a table contains an ID and a name) and I have to match them with another file which has the same ID and name.

I want to write a program in Perl to print out the result which will match the first table with the second, and print only the matching ID, name, sub-ID and date (last two fields from the second table).

Can anyone help me out with this?

This is what I already tried.

#!/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 "$line\n";
}

解决方案

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]};
}

--- in1 ---

name    id
foo 1
bar 2
baz 3
other   4

--- in2 ---

name    id
bar 1
baz 2
baz 3
other   4

这篇关于如何写一个算法在Perl读取两个文件的匹配数据,并打印查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆