file2.tabchr10 94055 94554 2 2 1 1 0 23 chr10 95850 122380 2 2 1 1 0 15 chr10 181243 196457 1 1 1 1 0 21 chr10 181243 225933 1 1 1 4 0 21 chr10 181500 225933 1 1 1 15 0 25 chr10 226069 255828 1 1 1 53 0 22 chr10 255948 267233 1 1 1 2 0 12 chr10 255989 267134 1 1 1 65 0 25 chr10 255989 282777 1 1 1 14 0 23 chr10 264440 267134 1 1 1 1 0 25
The columns in the files are tab separated. I want to combine the 2 files in a way that first 4 columns is used as a key and the value is the 7th column. If the key is missing in either file, the value for that key for that file should be 0. This is the output I would like:chr10 94055 94554 2 2 1 1 0 21 chr10 94055 94743 2 2 1 1 0 20 chr10 94666 94743 2 2 1 3 0 20 chr10 94853 95347 2 2 1 2 0 25 chr10 181243 225933 1 1 1 3 0 21 chr10 181500 225933 1 1 1 7 0 10 chr10 226069 255828 1 1 1 38 0 22 chr10 255989 267134 1 1 1 29 0 24 chr10 255989 282777 1 1 1 15 0 23 chr10 267297 282777 1 1 1 44 0 24
My code which is below, works perfectly fine, but I open my input files twice. Is there a way where I just have to open up the input files once? Code:chr fivep threep strand file1.tab file2.tab chr10 181500 225933 - 15 7 chr10 264440 267134 - 1 0 chr10 94055 94554 - 1 1 chr10 181243 225933 - 4 3 chr10 94666 94743 - 0 3 chr10 255989 282777 - 14 15 chr10 94853 95347 - 0 2 chr10 255948 267233 - 2 0 chr10 95850 122380 - 1 0 chr10 267297 282777 - 0 44 chr10 226069 255828 - 53 38 chr10 94055 94743 - 0 1 chr10 255989 267134 - 65 29 chr10 181243 196457 - 1 0
I have several input files and many more lines than the current dummy files I have shown here.#!/usr/bin/perl use strict; use warnings; my @files = glob("file*.tab"); my %output = (); foreach my $file ( @files ){ open(my $fh,'<',$file) or die $!; while(<$fh>){ chomp; my @s = split /\t/; die("_ERROR_ not 9 columns [ $_ ]\n") if (@s != 9); $output{$s[0]."\t".$s[1]."\t".$s[2]."\t".$s[3]} = []; } close $fh; } foreach my $file ( @files ){ foreach my $k(keys %output){ push @{$output{$k}},0; } open(my $fh,'<',$file) or die $!; while(<$fh>){ chomp; my @s = split /\t/; die("_ERROR_ not 9 columns [ $_ ]\n") if (@s != 9); my @array = @{$output{$s[0]."\t".$s[1]."\t".$s[2]."\t".$s[3]}} +; $array[-1] = $s[6]; $output{$s[0]."\t".$s[1]."\t".$s[2]."\t".$s[3]} = \@array; } close $fh; } print join("\t",'chr','fivep','threep','strand',@files),"\n"; foreach my $k(keys %output){ my @s = split /\t/,$k; my $chr = $s[0]; my $fivep = $s[1]; my $threep = $s[2]; my $strand = $s[3]; next if($strand =~ /^0$/); if($strand =~ /^0$/){ print join("\t",$chr,$fivep,$threep,"+",@{$output{$chr."\t".$f +ivep."\t".$threep."\t".$strand}} ),"\n"; }else{ print join("\t",$chr,$fivep,$threep,"-",@{$output{$chr."\t".$f +ivep."\t".$threep."\t".$strand}} ),"\n"; } }
In reply to open input files once by v15
For: | Use: | ||
& | & | ||
< | < | ||
> | > | ||
[ | [ | ||
] | ] |