2
votes

Im trying to sort a Hash using a list/array

my $hash =  {     cta => '01340031810312074443',
                  ttr => '001',fil => '0000',     
                  ref => '0000',
                  mef => '0000000000000060000',
                  mch => '0000000000000000000',
                  nli => '00000000',
                  tdi => 'V',
                  ndi => '006126952',
                  tdip => 'V',
                  ndip => '006126952',
              };

@order = qw(cta ttr fil ref mef mch nli tdi ndi tdip ndip);

We know Perl dont save orders in hash but I need to print in that order. How can I do that?

Thanks

3
How can you print the keys in the order that is stored in the array @order? Do you really need to think about that? - TLP
print $hash->{$_} for @order - TLP

3 Answers

7
votes

If you just want to print the values and not the keys, you can also use a hash slice:

use feature 'say';
say join "\t", @hash{@order};
2
votes
for my $key (@order) {
   print $key . ": " . $hash->{$key} . "\n";
}
1
votes

Try this:

for (@order) {
    print $_, " => ", $hash->{$_}, "\n";
}