sanku has asked for the wisdom of the Perl Monks concerning the following question:

hi monks, This is my program.
#!/usr/bin/perl open(FILE,"/Downloads/inputfile.txt") or die $!; while(<FILE>){ ($col1,$col2,$col3,$col4,$col15,$col6,$col7)=split(/\s+/,$_); @list=sort($col1,$col2,$col3,$col4,$col15,$col6); print @list; print "\n"; } close (FILE); my input file is like this c1p110 c2p452 9p235 8p226 5p100 6p218 c1p278 2p397 c6p280 7p273 3p409 my out put be like this 1 2 3 4 5 6 7 c1p278 2p397 3p409 c6p280 7p273 c1p110 c2p452 5p100 6p218
the out put should be displayed on particular column and also only the list which is having 2p397,2p409 like p element should be sorted only for p elements not for c Thanks in advance

Replies are listed 'Best First'.
Re: rearange the columns
by GrandFather (Saint) on Oct 31, 2008 at 09:43 UTC

    The key is to extract the column number from the column data then use that to place it in the table. Extracting stuff is what regexes do. Formatting the table is nicely done with printf. Consider:

    use warnings; use strict; use constant kMaxCol => 7; # print header printf "%5s ", $_ for 1 .. kMaxCol; print "\n"; # Process data while (<DATA>) { chomp; next unless length; my @cols = split (/\s+/, $_); my @sorted; @cols = map {[(m/(\d+)p/i ? $1 - 1 : kMaxCol), $_]} @cols; # Gener +ate indexes $sorted[$_->[0]] = $_->[1] for grep {$_->[0] >= 0 && $_->[0] < kM +axCol} @cols; $sorted[$_] ||= '' for 0 .. kMaxCol - 1; printf " %7s", $_ for @sorted; print "\n"; } __DATA__ c1p110 c2p452 9p235 8p226 5p100 6p218 c1p278 2p397 c6p280 7p273 3p409

    Prints:

    1 2 3 4 5 6 7 c1p110 c2p452 5p100 6p218 c1p278 2p397 3p409 c6p280 7p273

    Perl reduces RSI - it saves typing