in reply to sort an array
Well first of all that regex won't quite work, because the .+ will eat up all the digits, up the last one before the #. To prevent this, use (.+?).
Now then:
However, that's rather inefficient due to the fact that any given string gets parsed each time it's used in a comparison. Using the Schwartzian Transform is one way to alleviate this:@sorted = sort { my @a = $a =~ /^(.+?)(\d+)#(\d+)$/; my @b = $b =~ /^(.+?)(\d+)#(\d+)$/; $a[1] <=> $b[1] or $a[2] <=> $b[2] or $a[0] cmp $b[0] } @unsorted;
@sorted = map { $_->[0] } sort { $a->[2] <=> $b->[2] or $a->[3] <=> $b->[3] or $a->[1] cmp $b- +>[1] map { [ $_, /^(.+?)(\d+)#(\d+)$/ ] } @unsorted;
Maybe that's even easier to make sense of.
use Sort::Fields; my $sorter = make_stable_fieldsort( '(\d+)#', [ '2n', '3n', '1' ] ); my @sorted = $sorter->( @unsorted ); # voila
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: sort an array
by myffy (Acolyte) on Mar 19, 2006 at 07:53 UTC | |
by jonadab (Parson) on Mar 19, 2006 at 10:35 UTC | |
by jdporter (Paladin) on Mar 19, 2006 at 15:36 UTC | |
by jdporter (Paladin) on Mar 19, 2006 at 22:27 UTC | |
by tilly (Archbishop) on Mar 20, 2006 at 02:47 UTC | |
by jdporter (Paladin) on Mar 20, 2006 at 03:07 UTC | |
by Argel (Prior) on Mar 20, 2006 at 22:50 UTC | |
|