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;
🦛
In reply to Re: How can I do a numeric sort on a substring?
by hippo
in thread How can I do a numeric sort on a substring?
by misterperl
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |