I have a txt file like this:
#Genera columnA columnB columnC columnD columnN
x1 1 3 7 0.9 2
x2 5 3 13 7
You can simplify like this and using hash slices.
#!/usr/bin/env perl
use strict;
use warnings;
my @wanted = ( '#Genera' , qw ( columnA columnC columnN ));
open my $input, '<', "file.txt" or die $!;
chomp ( my @header = split ' ', <$input> );
print join "\t", @wanted, "\n";
while ( <$input> ) {
my %row;
@row{@header} = split;
print join "\t", @row{@wanted}, "\n";
}
Which outputs:
#Genera columnA columnC columnN
x1 1 7 2
x2 5 13 5
x3 0.1 7 0.4
If you want to exactly match your indentation then add sprintf
to the mix:
E.g.:
print join "\t", map { sprintf "%8s", $_} @wanted, "\n";
while ( <$input> ) {
my %row;
@row{@header} = split;
print join "\t", map { sprintf "%8s", $_} @row{@wanted}, "\n";
}
Which then gives:
#Genera columnA columnC columnN
x1 1 7 2
x2 5 13 5
x3 0.1 7 0.4