On Tue, 25 Mar 2014 09:55:25 -0400
shawn wilson <[email protected]> wrote:
> i want to sort an array for certain key words first and then
> alphabetically.
>
> my @foo = qw/foo bar baz first second third/;
>
> foreach my $i (sort {$a cmp $b} @foo) {
> print "$i\n";
> }
>
> How do I make 'first', 'second', and 'third' come before the rest?
> (I'm actually dealing with a hash)
>
Try:
my @foo = qw/foo bar baz first second third/;
my @preferences = qw( first second third );
my %preferences;
{
my $i = 1;
%preferences = map { $_ => $i++ } @preferences;
$preferences{''} = $i;
}
my @sorted_foo = map { $_->[0] }
sort { $a->[1] <=> $b->[1]
|| $a->[0] cmp $b->[0]
}
map { [ $_, $preferences{$_} || $preferences{''} ] }
@foo;
print "Unsorted: @foo\n";
print "Sorted: @sorted_foo\n";
--
Don't stop where the ink does.
Shawn
--
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]
http://learn.perl.org/