On Fri, Jul 24, 2009 at 11:01, Jo for lists and groups<ourli...@rogers.com> wrote: > How about this? Jo > > > > #!/usr/bin/perl > > use strict; > use warnings; > > my @list = qw/dog is a there/; > my @sortOrder = (3,1,2,0); > my @sorted; > foreach (@sortOrder) { push(@sorted,$list[$_]); } > > print "@sorted"; > exit; snip
What do you do when the list is qw/there a dog is/? Your code does not sort the data. I guess you could go insane and write something like: my %position = ( there => 0, is => 1, a => 2, dog => 3, ); for my $word (@list) { $sorted[$position{$word}] = $word; } But that would only work if the list will only contain one item each of "there", "is", "a", or "dog". The sort is not only more flexible, it is faster (due to the low number of items to be sorted and the fact that sort is implemented in C): positional_hash => there is a dog sort => there is a dog positional_array => there is a dog Rate positional_hash positional_array sort positional_hash 253734/s -- -11% -15% positional_array 284350/s 12% -- -5% sort 297890/s 17% 5% -- #!/usr/bin/perl use strict; use warnings; use List::Util qw/maxstr/; use Benchmark; my %position = ( there => 0, is => 1, a => 2, dog => 3, ); my @sortOrder = (3,1,2,0); my @a = qw/dog is a there/; my %subs = ( sort => sub { return join " ", sort { $position{$a} <=> $position{$b} } @a; }, positional_array => sub { my @sorted; push @sorted, $a[$_] for @sortOrder; return join " ", @sorted; }, positional_hash => sub { my @sorted; $sorted[$position{$_}] = $_ for @a; return join " ", @sorted; }, ); for my $sub (keys %subs) { print "$sub => ", $subs{$sub}->(), "\n"; } Benchmark::cmpthese -1, \%subs; -- Chas. Owens wonkden.net The most important skill a programmer can have is the ability to read. -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/