Bryan Harris wrote:
Let's say I have a bunch of lines of data in an array, @a:
car 72
car 55
truck 31
bike 2
car 12
truck 16
van 97
car 64
... and I want to sort them so that the trucks are first, then the vans,
the bikes are third, cars are next, and everything else sorted
alphabetically at the end.
I started down this route:
@a = sort {
if ($a =~ /^truck/ && $b =~ /^truck/) { 0 }
elsif ($a =~ /^truck/ && $b =~ /^van/) { -1 }
... } @a;
... but that quickly breaks down. Then I thought, what about this?:
@a = ( grep { /^truck/ } @a, grep { /^van/ } @a, grep { /^bike/ } @a,
grep { /^cars/ } @a, sort grep { !/^(truck|van|bike|cars)/ } @a);
... which seems to work, but looks clunky, feels like it'd be slow, and
doesn't scale well if my list of 5 things were to become 75.
How is this kind of thing usually done?
my %order = (
truck => 0,
van => 1,
bike => 2,
car => 3,
'' => 4
);
my $regex = qr/^(truck|van|bike|car)/;
my @sorted = sort { $order{ ( $a =~ $regex )[ 0 ] } <=> $order{ ( $b =~
$regex )[ 0 ] } || $a cmp $b } @a;
Strikingly beautiful. Thank you.
Do you have a library of code snippets that you pulled this from? I would
love to buy a copy from you.
- Bryan
--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/