in reply to Sorting records on a single field

Hi! I don't have extensive experience with sorting methods, but in this case I think a simple approach would work, like that:

use strict; use warnings; my $Line; # one input line my @SortedData; # resulting sorted data set # data set example my @Data = ( '100644:MWTP_CAT:12002: SERVER:pid=14520:Execution + time:TPR015-10:(millisec):53', '100644:MWTP_CAT:12002: SERVER:pid=15866:Execution + time:TPR015-10:(millisec):10', '100644:MWTP_CAT:12002: SERVER:pid=15866:Execution + time:TPR015-10:(millisec):33', '100644:MWTP_CAT:12002: SERVER:pid=16565:Execution + time:TPR007-12:(millisec):437', '100644:MWTP_CAT:12002: SERVER:pid=16565:Execution + time:TPR007-12:(millisec):470', '100644:MWTP_CAT:12002: SERVER:pid=16048:Execution + time:TPR009-30:(millisec):24', '100644:MWTP_CAT:12002: SERVER:pid=15866:Execution + time:TPR012-01E:(millisec):63', '100644:MWTP_CAT:12002: SERVER:pid=10427:Execution + time:ISCST044:(millisec):0', '100644:MWTP_CAT:12002: SERVER:pid=15866:Execution + time:TPR012-01E:(millisec):85', '100644:MWTP_CAT:12002: SERVER:pid=10428:Execution + time:01201E:(millisec):3', ); # create sorted data set @SortedData = reverse sort { (split (/:/, $a))[-1] <=> (split (/:/, $b +))[-1] } @Data; ### DEBUG: print input and output sets ### print "Data Set is:\n", join ("\n", @Data), "\n"; print "Sorted Data is:\n", join ("\n", @SortedData), "\n";

Replies are listed 'Best First'.
Re^2: Sorting records on a single field
by salva (Canon) on Jan 21, 2010 at 10:40 UTC
    You can get rid of the reverse operation just inverting the order of the comparison operands. In other words, instead of reverse sort { $a <=> $b } @data use sort { $b <=> $a } @data.

    In OP case:

    @SortedData = sort { (split (/:/, $b))[-1] <=> (split (/:/, $a))[-1] } + @Data;

    Using reverse also makes the sort operation unstable (entries with equal sorting keys do not keep their relative positions after the sort operation).

      I see that switching the opereands is better but I don't catch what you mean with "equal sorting keys do not keep their relative positions after the sort operation"... probably I miss something. Could you explain deeply that point? Thanks.

        Sure! Let me do it with an example:
        my @data = qw(1a 1b 2a 2b); my @s1 = reverse sort { $a <=> $b } @data; my @s2 = sort { $b <=> $a } @data; print "@s1\n@s2\n";
        generates:
        2b 2a 1b 1a 2a 2b 1a 1b
        Note how in the second row, elements with the same sorting key (the numeric part) appear in the same order they had in @data while in the first row, corresponding to the reverse solution, they do not.