in reply to Perl Sorting One Liner
G'day Siccula,
Welcome to the monastery.
Here's an example showing various techniques used in sorting columns:
$ perl -Mstrict -Mwarnings -E ' use constant { FIRST => 0, SECOND => 1, THIRD => 2 }; my @data = qw{ A:C:1 A:C:2 A:D:1 A:D:2 B:C:1 B:C:2 B:D:1 B:D:2 }; say "Raw data:"; say for @data; say "Sorted data:"; say join ":" => @$_ for sort { $b->[FIRST] cmp $a->[FIRST] || $a->[SECOND] cmp $b->[SECOND] || $b->[THIRD] <=> $a->[THIRD] } map { [ split /:/ ] } @data; ' Raw data: A:C:1 A:C:2 A:D:1 A:D:2 B:C:1 B:C:2 B:D:1 B:D:2 Sorted data: B:C:2 B:C:1 B:D:2 B:D:1 A:C:2 A:C:1 A:D:2 A:D:1
Here, FIRST column is sorted into descending alphabetical order; where items are the same, SECOND column is sorted into ascending alphabetical order; where items are the same, THIRD column is sorted into descending numerical order.
References: sort; perlvar (for $a and $b); perlop (for cmp and <=>).
Decide whether sorting will be applied to more than one column and, if so, what order to use. For instance, to sort by last name and then, if last names are the same, sort by first name, you might use something like:
$a->[LAST_NAME] cmp $b->[LAST_NAME] || $a->[FIRST_NAME] cmp $b->[FIRST +_NAME]
Look at the type of data you're sorting and use the appropriate operator: cmp for strings and <=> for numbers.
For ascending sorts (0 -> 9, A -> Z, etc.) compare $a data to $b data (e.g. $a->[SECOND] cmp $b->[SECOND]); for descending sorts, reverse the $a and $b values (e.g. $b->[THIRD] <=> $a->[THIRD]).
I've implemented the example as a one-liner (albeit with some formatting for readability purposes). So, for a one-off, throw-away command line, a one-liner is fine; however, save the code to a script if you're ever going to: run this again; need a record of what code you used; want to refer back to it to refresh your memory on how to do this.
-- Ken
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Perl Sorting One Liner
by educated_foo (Vicar) on May 07, 2013 at 14:17 UTC | |
by Anonymous Monk on May 07, 2013 at 15:15 UTC | |
by educated_foo (Vicar) on May 07, 2013 at 16:11 UTC | |
by Anonymous Monk on May 07, 2013 at 16:30 UTC | |
by educated_foo (Vicar) on May 07, 2013 at 16:39 UTC | |
|