in reply to Extracting selected column names and values from tab delimited text file

Here is another solution variant for you. The problem is easier if you are working with column numbers instead of names for the selection criteria. But I did that conversion for you. Column print order is same order as names in @desired_cols.

Code winds up with an ordered list of column positions to print and then does that for the data in the file by using list slice.

#!/usr/bin/perl -w use strict; my @desired_cols = qw(colname1 colname3); #order matters here # reads first line to get actual column names my $header_line = (<DATA>); my @actual_cols = split(/\s+/,$header_line); # get column number of the actual column names my $pos =0; my %col2_num = map {$_ => $pos++}@actual_cols; # translate the desired col names into position numbers my @slice = map{$col2_num{$_}}@desired_cols; print join("\t",@desired_cols),"\n"; #header line while (<DATA>) { my @row = (split)[@slice]; print join("\t",@row),"\n"; #each data row } =pod Prints: colname1 colname3 val1 val3 val11 val31 val12 val32 =cut __DATA__ colname1 colname2 colname3 val1 val2 val3 val11 val21 val31 val12 val22 val32
  • Comment on Re: Extracting selected column names and values from tab delimited text file
  • Download Code

Replies are listed 'Best First'.