On Tue, 5 Aug 2003, Adam Witney wrote:

> Date: Tue, 05 Aug 2003 16:12:50 +0100
> From: Adam Witney <[EMAIL PROTECTED]>
> To: MacOS X perl <[EMAIL PROTECTED]>
> Subject: Ordering keys in a hash
>
> Hi,
>
> I have a hash with keys of the format
>
> sar0011_4
> sar0203_3
> sar0050_5
> sar2001_1
> sar0002_9
>
> And I would like to generate a list ordered by the \d\d\d\d bit in the
> middle. I have this from the perl cookbook
>
> my @keys = sort {criterion()} keys(%gene_pool);
>
> but I don't really know how to approach the criterion() function
>
> Anybody have any suggestions?
>
> Thanks for any help
>
> Adam

I don't know how many values you need to sort, but it's probably
advisable to use a Schwartzian Transform.  Here's my suggestion:

    my @sorted =
        map  { $_->[1] }
        sort { $a->[0] <=> $b->[0] }
        map  { [ $_ =~ /(\d{4})/, $_ ] }
        qw( sar0011_4 sar0203_3 sar0050_5 sar2001_1 sar0002_9 );

    print "Sorted = ", join(', ', @sorted), "\n";

Gives me:

    Sorted = sar0002_9, sar0011_4, sar0050_5, sar0203_3, sar2001_1

Is that what you want?

ky

Reply via email to