code:
#!/usr/bin/perl use strict; use warnings; use Data::Dumper; use Tie::IxHash; my %hash = ( g=>10, i=>55, k=>4, n=>100, ); my %sorted_hash; tie %sorted_hash, "Tie::IxHash"; my @array = ('k','i','n','g'); foreach(@array) { if(defined($hash{$_})) { $sorted_hash{$_} = $hash{$_}; } } print Dumper(%sorted_hash);
Print
$VAR1 = 'k'; $VAR2 = 4; $VAR3 = 'i'; $VAR4 = 55; $VAR5 = 'n'; $VAR6 = 100; $VAR7 = 'g'; $VAR8 = 10;
Mention that I used the Tie :: ixHash module. Otherwise, Perl will not sort the keys of the array.
This Perl module implements Perl hashes that preserve the order in which the hash elements were added.
http://metacpan.org/pod/Tie::IxHash
source share