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

I have the following hash, and I want to save it in the order in which I set it; is it even possible? If not, are there any alternatives?

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

Do I need to write a custom sort routine? What are my options?

Thanks!

+4
source share
5 answers

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

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

This hash will keep its order.

+8
source

See Tie :: Hash :: Indexed . Quoting his brief review:

 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' 
+2
source

Try to do this:

 print "$_=$hash{$_}\n" for sort keys %hash; 

if you want it to be sorted alphabetically.

If you need to keep the original order, see other posts.

See http://perldoc.perl.org/functions/sort.html

+1
source

One possibility is to do what you sometimes do with arrays: specify the keys.

  for (0..$#a) { # Sorted array keys say $a[$_]; } for (sort keys %h) { # Sorted hash keys say $h{$_}; } for (0, 1, 3) { # Sorted array keys say $h{$_}; } for (qw( Key1 Key2 Key3 )) { # Sorted hash keys say $h{$_}; } 

You can also get ordered values โ€‹โ€‹as follows:

  my @values = @h{qw( Key1 Key2 Key3 )}; 
+1
source

It depends on how you are going to access the data. If you just want to save them and access the last / first values, you can always put hashes in an array and use push () and pop ().

 #!/usr/bin/env perl use strict; use warnings; use v5.10; use Data::Dumper; my @hashes; foreach( 1..5 ){ push @hashes, { "key $_" => "foo" }; } say Dumper(\@hashes); 
0
source

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


All Articles