Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting a hash from the first key to the last (Perl)

Tags:

sorting

hash

perl

I have the following hash, and I wish to keep it in the order I've set it in; is this even possible? If not, do any alternatives exist?

my %hash = ('Key1' => 'Value1', 'Key2' => 'Value2', 'Key3' => 'Value3');

Do I need to write a custom sorting subroutine? What are my options?

Thank you!

like image 854
user1807879 Avatar asked Dec 15 '22 17:12

user1807879


2 Answers

http://metacpan.org/pod/Tie::IxHash

use Tie::IxHash;
my %hash;
tie %hash,'Tie::IxHash';

This hash will maintain its order.

like image 129
ugexe Avatar answered Jan 08 '23 13:01

ugexe


See Tie::Hash::Indexed. Quoting its Synopsis:

use Tie::Hash::Indexed;

tie my %hash, 'Tie::Hash::Indexed';

%hash = ( I => 1, n => 2, d => 3, e => 4 );
$hash{x} = 5;

print keys %hash, "\n";    # prints 'Index'
print values %hash, "\n";  # prints '12345'
like image 31
choroba Avatar answered Jan 08 '23 13:01

choroba