for (sort by_seq([qw(five nine one seven three)]), keys %h) { #### use strict; #use diagnostics; sub by_seq { my $seq_aref = shift; my %seq_helper; { my $index = 0; for my $item (@{ $seq_aref }) { $seq_helper{$item} = $index; $index++; }; }; # Here I return a subroutine that takes two arguments # (the left and the right element to be compared) return sub { $seq_helper{$_[0]} <=> $seq_helper{$_[1]} }; }; # -- my %h = (one=>2,three=>4,five=>6,seven=>8,nine=>0); # Create our custom comparison routine my $sorter = by_seq([qw(five nine one seven three)]); for (sort {$sorter->($a,$b)}, keys %h) { print "$_: $h{$_}\n"; };