Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Perl, how can I sort hash keys using a custom ordering?

I am trying to do work on a hash of files and the work has to be done in a specific order. Most would say the list can be ordered like so:

for my $k (sort keys %my_hash)
{
    print "$k=>$my_hash{$k}, ";
}

However, I need nonalphabetical order, in fact the keys start with a word then _ and they go G to digits to L to any of M,P,R,T or D (eg. word_G.txt,word_2.txt,...,word_P.txt). Is there any way to sort by custom order?

like image 310
Eric Fossum Avatar asked Nov 17 '11 17:11

Eric Fossum


1 Answers

Is there any way to sort by custom order?

Yes. See sort.

For example:

#!/usr/bin/env perl

use warnings; use strict;

my @order = qw(G 1 2 3 L M P R T D);

my %order_map = map { $order[$_] => $_ } 0 .. $#order;

my $pat = join '|', @order;

my @input = qw(word_P.txt word_2.txt word_G.txt);

my @sorted = sort {
    my ($x, $y) = map /^word_($pat)[.]txt\z/, $a, $b;
    $order_map{$x} <=> $order_map{$y}
} @input;

print "@sorted\n";
like image 53
Sinan Ünür Avatar answered Nov 15 '22 05:11

Sinan Ünür