Jabda
Jabda

Reputation: 1792

Sort by subset of a Perl string

I have a hash. The hash key is a long string, "str_3432_123_A12_C02_xy_ut", and I want to sort the keys by a subset of the string which will have the format A12_C02.

I assume no other part of the string will match the regex, but the location inside the string can differ.

 [A-Za-z][0-9]{2}_[A-Za-z][0-9]{2}

To sort my hash by keys:

  my @sorted = sort keys %myhash;

I also have a separate array for all the values that could possibly match.

Upvotes: 2

Views: 352

Answers (2)

Qtax
Qtax

Reputation: 33908

At least if it's not a huge sort, a trivial solution would be to use sort directly:

my $re = /([a-z][0-9]{2}_[a-z][0-9]{2})/i;
my @sorted = sort {
        ($a) = $a =~ $re;
        ($b) = $b =~ $re;
        $a cmp $b;
    }
    keys %hash;

Upvotes: 4

Birei
Birei

Reputation: 36262

Use a combination of map and sort to extract the part of the string you want to use to sort and recover the whole key once done, like:

my @sorted = 
    map { $_->[0] } 
    sort { $a->[1] cmp $b->[1] } 
    map { m/([A-Za-z][0-9]{2}_[A-Za-z][0-9]{2})/ && [$_, $1] } 
    keys %myhash;

Upvotes: 3

Related Questions