Thanks (y'all). Though, I like this one best I think. BTW, Jim's isn't exactly correct: my @keys = qw( foo bar second baz first third );
my %primary = ( second => 1, first => 1, third => 1); And then the output becomes: Sorted: first, second, third, bar, baz, foo Which isn't correct. On Tue, Mar 25, 2014 at 10:45 AM, Shawn H Corey <shawnhco...@gmail.com> wrote: > On Tue, 25 Mar 2014 09:55:25 -0400 > shawn wilson <ag4ve...@gmail.com> 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: beginners-unsubscr...@perl.org > For additional commands, e-mail: beginners-h...@perl.org > http://learn.perl.org/ > > -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/