On Mar 25, 2014, at 6:55 AM, 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)


You need to write a sort comparison function that will return:
  -1 if $a is a primary key and $b is not
  +1 if $b is a primary key and $a is not
  a normal comparison value if either both or neither are a primary key

Here is one way:

#!/usr/bin/perl
use strict;
use warnings;

my @keys = qw( foo bar baz first second third );

my %primary = ( first => 1, second => 1, third => 1);

my @sorted;
@sorted = sort {
        if( ! ($primary{$a} xor $primary{$b}) ) {
                return $a cmp $b;
        }elsif( $primary{$a} ) {
                return -1;
        }else{
                return +1;
        } } @keys;
        
print "Sorted: ", join(', ',@sorted), "\n”;

You could also prepend ‘1’ to your primary keys and ‘2’ to the other keys, do 
the sort, then strip the digits.




--
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]
http://learn.perl.org/


Reply via email to