我的问题类似于之前发布的这个问题。
我有很多文件,我需要根据第一列 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";
}