in reply to sorting an array with decimal points
this is a typical case for using the Schwartzian Transform (see https://en.wikipedia.org/wiki/Schwartzian_transform):
The map on the last line creates an anonymous array in which the items are array refs containing the whole string, the first number and the second number (for example: [Patch_11.4, 11, 4]). The items are then sorted according to the first number and then according to the second number. At the end, the map on the first line retrieves the original strings from the sorted array refs.use strict; use warnings; use feature "say"; my @array = qw(Patch_11.4 Patch_1.0 Patch_2.0 Patch_3.1 Patch_5.0 Patc +h_4.2 Patch_6.0 Patch_11.0 Patch_7.0 Patch_8.0 Patch_9.3 Patch_10.2 Pat +ch_11.2); @array = map { $_->[0] } sort { $a->[1] <=> $b->[1] or $a->[2] <=> $b->[2] } map { /Patch_(\d+)\.(\d+)/; [$_, $1, $2] } @array; say for @array;
Output:
$ perl sort_versions.pl Patch_1.0 Patch_2.0 Patch_3.1 Patch_4.2 Patch_5.0 Patch_6.0 Patch_7.0 Patch_8.0 Patch_9.3 Patch_10.2 Patch_11.0 Patch_11.2 Patch_11.4
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: sorting an array with decimal points
by kcott (Archbishop) on Jan 15, 2018 at 00:02 UTC | |
by Laurent_R (Canon) on Jan 15, 2018 at 07:26 UTC | |
|
Re^2: sorting an array with decimal points
by levW (Beadle) on Jan 14, 2018 at 11:13 UTC |