Sort a hash as keys in an array

I have a hash

%value g=>10 i=>55 k=>4 n=>100 

I have an array

 @letters = ('k','i','n','g') 

please let me know how to sort the hash in the order of the keys in the array.

+4
source share
2 answers

If you want to print the hash values ​​in the order they appear in the @letters array, then

 print join ",", @value{@letters}; 
+5
source

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

+4
source

Source: https://habr.com/ru/post/1483839/


All Articles