我的问题类似于之前发布的question。
我有很多文件需要根据第一列ID的存在与否来合并它们,但是在合并时我的输出文件中有很多空值,我希望那些空值为零它不存在于另一个文件中。下面的示例仅基于两个文件内容,但我有许多样本文件,如此格式(表格)。
例如:
File1
ID Value
123 1
231 2
323 3
541 7
File2
ID Value
541 6
123 1
312 3
211 4
Expected Output:
ID File1 File2
123 1 1
231 2 0
323 3 0
541 7 6
312 0 3
211 0 4
Obtaining Output:
ID File1 File2
123 1 1
231 2
323 3
541 7 6
312 undef 3
211 undef 4
正如你在上面看到的那样,我得到了输出,但在file2列中,它没有添加零或留空,而在file1列的情况下,它具有undef值。我检查了undef值,然后我的最终输出给出零代替undef值,但我仍然有那些空格。请在下面找到我的代码(仅对两个文件进行硬编码)。
#!/usr/bin/perl
use strict;
use warnings;
use diagnostics;
use Data::Dumper;
my $path = "/home/pranjay/Projects/test";
my @files = ("s1.txt","s2.txt");
my %classic_com;
my $cnt;
my $classic_txt;
my $sample_cnt = 0;
my $classic_txtcomb = "test_classic.txt";
open($classic_txt,">$path/$classic_txtcomb") or die "Couldn't open file
$classic_txtcomb for writing,$!";
print $classic_txt "#ID\t"."file1\tfile2\n";
foreach my $file(@files){
$sample_cnt++;
print "$sample_cnt\n";
open($cnt,"<$path/$file")or die "Couldn't open file $file for reading,$!";
while(<$cnt>){
chomp($_);
my @count = ();
next if($_=~/^ID/);
my @record=();
@record=split(/\t/,$_);
my $scnt = $sample_cnt -1;
if((exists($classic_com{$record[0]})) and ($sample_cnt > 0)){
${$classic_com{$record[0]}}[$scnt]=$record[1];
}else{
$count[$scnt] = "$record[1]";
$classic_com{$record[0]}= [@count];
}
}
}
my %final_txt=();
foreach my $key ( keys %classic_com ) {
#print "$key: ";
my @val = @{ $classic_com{$key} };
my @v;
foreach my $i ( @val ) {
if(not defined($i)){
$i = 0;
push(@v, $i);
}else{
push(@v, $i);
next;
}
}
$final_txt{$key} = [@v];
}
#print Dumper %classic_com;
while(my($key,$value)=each(%final_txt)){
my $val=join("\t", @{$value});
print $classic_txt "$key\t"."@{$value}"."\n";
}
答案 0 :(得分:3)
只需将输入文件读入数组哈希即可。最上面的键是ID,每个内部数组包含 i -th位置上的文件 i 的值。打印时,使用//
已定义或运算符将undef替换为零:
#!/usr/bin/perl
use warnings;
use strict;
use feature qw{ say };
my %merged;
my $file_tally = 0;
while (my $file = shift) {
open my $in, '<', $file or die "$file: $!";
<$in>; # skip the header
while (<$in>) {
my ($id, $value) = split;
$merged{$id}[$file_tally] = $value;
}
++$file_tally;
}
for my $value (keys %merged) {
my @values = @{ $merged{$value} };
say join "\t", $value, map $_ // 0, @values[0 .. $file_tally - 1];
}
答案 1 :(得分:1)
program.pl
my %val;
/ (\d+) \s+ (\d+) /x and $val{$1}{$ARGV} = $2 while <>;
pr( 'ID', my @f = sort keys %{{map%$_,values%val}} );
pr( $_, map$_//0, @{$val{$_}}{@f} ) for sort keys %val;
sub pr{ print join("\t",@_)."\n" }
执行命令
perl program.pl s1.txt s2.txt
ID s1.txt s2.txt
123 1 1
211 0 4
231 2 0
312 0 3
323 3 0
541 7 6