On Mar 25, 2014, at 7:56 AM, shawn wilson <ag4ve...@gmail.com> wrote:
> 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. I humbly beg to differ. Your specification was to sort ‘first’, ‘second’, or ‘third’ before other keys, and the solution I provided does exactly that, sorting ‘first’, ‘second’, and ‘third’ in alphabetic order before the other keys. The values assigned to the %primary hash are irrelevant and are not used in any comparison. The existence of the key,value pair in the hash is used to specify which keys are the primary ones. If you want to specify what order the primary keys should occur, rather than simple alphabetic order, then you will have to modify the program: #!/usr/bin/perl use strict; use warnings; my @keys = qw/foo bar baz first second third/; my %primary = ( first => 3, second => 2, third => 1); # different values for each key giving sort order (1, 2, 3, etc.) my @sorted; @sorted = sort { if( $primary{$a} && $primary{$b} ) { return $primary{$a} <=> $primary{$b}; }elsif( $primary{$a} ) { return -1; }elsif( $primary{$b} ) { return +1; }else{ return $a cmp $b; } } @keys; print "Sorted: ", join(', ',@sorted), "\n"; Producing: Sorted: third, second, first, bar, baz, foo -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/