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

This is actually related to the earlier "Data Structure Advice" post.

I received some great advice, but now I realize I have to sort on a third column that consists of characters.

This is the code I'm using for the sort routine:

@data = numeric_sorter(2,0, @data); &print; # Print the contents of the array sub print { foreach my $record (@data ) { for my $i (0 .. 4) { print $record->[$i] . " "; } print "\n"; } } # First sort using the 3rd element of the array(port) and if it's the +same # sort by looking at the 1st element(time) sub numeric_sorter { my ($field_num, $field_num_secondary, @data) = @_; my @sorted_items = sort { if ($a->[$field_num] != $b->[$field_num]) { $a->[$field_num] <=> $b->[$field_num] } else { $a->[$field_num_secondary] <=> $b->[$field_num_secondary] } } @data; return @sorted_items; }
Is it possible to sort the fourth col., after a tie on the first column ?
BEFORE SORT: col1 col2 col3 col4 col 5 1040564312 z 89 In 258381720 1040564312 z 89 Out 4194077715 1040564322 z 90 Out 4194081727 1040564322 z 90 In 258385268 1040564335 z 94 IN 4194085256 1040564335 z 94 Out 4194085196 DESIRED SORT: (col4) col1 col2 col3 col4 col 5 1040564312 z 89 In 258381720 1040564312 z 89 Out 4194077715 1040564322 z 90 In 258385268 1040564322 z 90 Out 4194081727 1040564335 z 94 IN 4194085256 1040564335 z 94 Out 4194085196

Replies are listed 'Best First'.
Re: Sort 3X
by sauoq (Abbot) on Nov 23, 2002 at 03:20 UTC

    The usual idiom for this is to use the short circuiting provided by ||.

    @data_sorted_by_three_fields = sort { $a->[2] <=> $b->[2] || $a->[0] <=> $b->[0] || $a->[4] <=> $b->[4] } @data;
    -sauoq
    "My two cents aren't worth a dime.";
    
      Thanks, I don't know why I didn't think of that

      Thanks again!

Re: Sort 3X
by hydo (Monk) on Nov 23, 2002 at 04:07 UTC
    I'm compelled to ask this as more of a general question than direct to the poster. Wouldn't defining 'print' as a sub in a script be a "Bad Thing"? Obviously it is syntactically correct but I thought that redefining common functions wasn't a good idea just as a general rule.