http://www.perlmonks.org?node_id=924308


in reply to reformatting tab delimited file

Text::Table will align your output. Here is a sample program. Also, I used Sort::Naturally so that names with trailing digits will sort correctly, i.e. when they are greater than 1 digit long.

Update: in while loop, changed from split on space to split on tabs because thats how the fields are separated.

#!/usr/bin/perl use strict; use warnings; use Text::Table; use Sort::Naturally; my %data; my @col2 = qw/ PA TT AT /; while (<DATA>) { chomp; my ($name, $col2, $col3) = split /\t/; push @{ $data{$name}{$col2} }, $col3; } my $tb = Text::Table->new( map {title => $_}, @col2); for my $name (nsort keys %data) { my @tmp; local $" = ','; for my $col2 (@col2) { push @tmp, $data{$name}{$col2} ? "@{ $data{$name}{$col2} }" : ""; } $tb->load(\@tmp); } print $tb; __DATA__ Name_1 TT XL_927799.1 Name_1 PA PA_392 Name_1 AT ZX_003039195.1 Name_2 TT XL_931313.1 Name_2 AT ZX_003043016.1 Name_3 TT XL_929616.1 Name_3 PA PA_5040 Name_3 PA PA_6336 Name_4 TT XL_928294.1 Name_4 PA PA_917

This prints:

PA TT AT PA_392 XL_927799.1 ZX_003039195.1 XL_931313.1 ZX_003043016.1 PA_5040,PA_6336 XL_929616.1 PA_917 XL_928294.1

Replies are listed 'Best First'.
Re^2: reformatting tab delimited file
by garyboyd (Acolyte) on Sep 06, 2011 at 09:03 UTC

    Thanks for everybody's suggestions, the solution provided by Cristoforo works brilliantly!