Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

order hash perl using another array

Tags:

sorting

perl

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

like image 457
user2321170 Avatar asked Jun 23 '26 13:06

user2321170


2 Answers

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};
like image 52
Ilmari Karonen Avatar answered Jun 26 '26 18:06

Ilmari Karonen


for my $key (@order) {
   print $key . ": " . $hash->{$key} . "\n";
}
like image 24
Paul Roub Avatar answered Jun 26 '26 18:06

Paul Roub