Hi Shawn,
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)
>
Do something like that:
[CODE] # Tested but not extensively.
#!/usr/bin/perl
use strict;
use warnings;
my @foo = qw/foo bar baz first second third/;
my @positions = qw/first second third/;
my %pos = (map { $positions[$_] => $_+1 } keys(@positions));
my $max_pos = @positions+2;
sub _get_pos
{
my $k = shift;
return exists($pos{$k}) ? $pos{$k} : $max_pos;
}
my @foo_sorted =
sort
{
my $a_pos = _get_pos($a);
my $b_pos = _get_pos($b);
($a_pos <=> $b_pos) or ($a cmp $b);
}
@foo;
foreach my $i (@foo_sorted)
{
print "$i\n";
}
[/CODE]
It is a good idea to make a judicious use of the "or"/"||" operators when it
comes to sorting.
Hope it helps.
Regards,
Shlomi Fish
--
-----------------------------------------------------------------
Shlomi Fish http://www.shlomifish.org/
First stop for Perl beginners - http://perl-begin.org/
Gödel’s Incompleteness Theorem is about to be replaced by the
[Clarissa] Darling “Like, Totally!” Completeness Theorem.
— http://www.shlomifish.org/humour/bits/facts/Clarissa/
Please reply to list if it's a mailing list post - http://shlom.in/reply .
--
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]
http://learn.perl.org/