in reply to How can I sort this data on the fourth field?

I'd use merlyn's Schwartzian Transform:
chomp ( my @data = <DATA> ); my @sorted = map { $_->[0] } sort { $a->[1] <=> $b->[1] } map [ $_, (split)[3] ], @data; print "$_\n" for @sorted; __DATA__ 0 TOTAL 11997 26981 0 root 1089 2594 1 daemon 0 0 594 pipmp01 591 1151 958 maestro 335 685

Output:

1 daemon 0 0 958 maestro 335 685 594 pipmp01 591 1151 0 root 1089 2594 0 TOTAL 11997 26981

Replies are listed 'Best First'.
Re^2: How can I sort this data on the fourth field?
by country1 (Acolyte) on Aug 16, 2007 at 12:29 UTC


    FunkyMonk,


    I am not sure where to insert this into my perl code. I am reading this data in from a file and I am
    skipping some lines of input. The beginning code is as follows:

    for my $file ("may_07_xsd00544.dat") { open (my $fh,"<",$file) or die "Can't open file $file: $!"; while (my $line = <$fh>) { chomp($line); last if ($line =~ /TOTAL COMMAND SUMMARY/); next if (($line =~ /^[a-zA-Z]/) or ($line =~ /^\s*$/) or ($line =~ /^ +\s/));
      You need to build an array (with push @data, $line;) inside your while loop, between that next and the closing brace.

      The sort snippet I posted should be placed after the closing brace of the while.

      Something like:

      my @data; while (my $line = <$fh>) { chomp($line); last if ($line =~ /TOTAL COMMAND SUMMARY/); next if (($line =~ /^[a-zA-Z]/) or ($line =~ /^\s*$/) or ($line =~ / +^\s/)); push @data, $line; } my @sorted = map { $_->[0] } sort { $a->[1] <=> $b->[1] } map [ $_, (split)[3] ], @data;

      Going on the data you posted, wouldn't that next be better written as:

      next unless $line =~ /^\d/;


        I am executing the following code per your recommendations
        and am getting no print output.

        #!/usr/bin/perl use strict; use warnings; ########################################################## # # Parse PS Accounting Data # ########################################################## my $uid; my $login; my $cpupr; my %someData; my $value; my $key; for my $file ("may_07_xsd00544.dat") { open (my $fh,"<",$file) or die "Can't open file $file: $!"; my @data; while (my $line = <$fh>) { chomp($line); chomp ( my @data = <$fh> ); last if ($line =~ /TOTAL COMMAND SUMMARY/); next unless $line =~ /^\d/; push @data, $line; } my @sorted = map { $_->[0] } sort { $b->[1] <=> $a->[1] } map [ $_, (split)[3] ], @data; print "$_\n" for @sorted; close $fh or die "Can't close result file: $!"; }


        I modified the sort code to do a descending numeric sort on the 4th column.