in reply to How can I do a numeric sort on a substring?
The general case would be to use a Schwartzian Transform but in this simplistic case for small values of n you can just perform the extractions within the sort:
use strict; use warnings; use Test::More tests => 1; my @in = qw/a-3 a-1 a-2/; my @want = qw/a-1 a-2 a-3/; my @have = sort { ($a =~ /(\d+)/)[0] <=> ($b =~ /(\d+)/)[0] } @in; is_deeply \@have, \@want;
See also the FAQ: How do I sort an array by (anything)?
PS. Here's the same thing but with substr:
use strict; use warnings; use Test::More tests => 1; my @in = qw/a-3 a-1 a-2/; my @want = qw/a-1 a-2 a-3/; my @have = sort { substr ($a, 2) <=> substr ($b, 2) } @in; is_deeply \@have, \@want;
🦛
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: How can I do a numeric sort on a substring?
by misterperl (Friar) on Jun 25, 2021 at 14:01 UTC | |
by haukex (Archbishop) on Jun 25, 2021 at 14:07 UTC | |
by LanX (Saint) on Jun 25, 2021 at 16:48 UTC | |
by misterperl (Friar) on Jun 25, 2021 at 14:15 UTC | |
by misterperl (Friar) on Jun 25, 2021 at 14:09 UTC | |
by BillKSmith (Monsignor) on Jun 25, 2021 at 15:56 UTC | |
by salva (Canon) on Jun 28, 2021 at 09:25 UTC | |
| |
by hippo (Archbishop) on Jun 25, 2021 at 15:12 UTC |