Hi syphilis
I first thought it would never work because 10.1 would come before 2.1, but then, thinking back about it, I wondered whether it might actually work thanks to the coercion of version numbers into decimal numbers imposed by the <=> operator, but I wasn't quite sure. So, I just tried it, and yes, it does work properly:
$ perl -e '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 Pa
+tch_4.2 Patch_6.0
> Patch_11.0 Patch_7.0 Patch_8.0 Patch_9.3 Patch_10.2 P
+atch_11.2);
> my @array2 = sort { substr($a, 6) <=> substr($b, 6)} @array;
> say for @array2;
> '
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
| [reply] [d/l] [select] |
Hi Laurent_R,
it might actually work thanks to the coercion of version numbers into decimal numbers imposed by the <=> operator
Yes, the spaceship operator will always compare in numeric context - and I was quite confident that if the only problem with levW's
sort { substr($a, 6,2) <=> substr($b, 6,2)} @array
was that it failed to sort in the correct order, then
sort { substr($a, 6) <=> substr($b, 6)} @array
would fix that.
But levW seemed to think that there was a problem re the decimal point (which I don't see), and I was a little unsure about other aspects of the requirements, so I shied away from investing much time into my reponse.
Cheers, Rob | [reply] [d/l] [select] |
Yes, the reason I answered your post was that I thought other monks might make the same mistake I initially made: that's why I thought it was worth showing that your solution worked for the sample data shown because of numeric coercion, and also to show the test.
This being said, and as pointed out by AnomalousMonk in Re: sorting an array with decimal points, if the OP's data is really representing version numbers (and I think that's what they are) and not decimals, then your solution would fail on, for example, 5.2, 5.14, 5.16, 5.20, because it would sort 5.2 after 5.14 and 5.16 (which would be wrong for version numbers).
But, of course, my assumptions that they are version numbers may also be wrong. Only levW can tell us what they really are.
| [reply] [d/l] |
| [reply] |
I understand that you already have a great solution. However, if you prefer a solution which implements your specification exactly, you can use another module (List::UtilsBy).
use strict;
use warnings;
use List::UtilsBy qw(nsort_by);
my @array = qw(Patch_1.0 Patch_2.0 Patch_3.1 Patch_5.0 Patch_4.2
Patch_6.0 Patch_7.0 Patch_8.0 Patch_9.3 Patch_10.2);
{
local $, = "\n";
print nsort_by {s/Patch_//} @array
}
UPDATE: Added link.
| [reply] [d/l] |