user6039980 user6039980 - 4 months ago 16
Perl Question

Perl: How to save keys order from hash?

I'm trying to display the keys from json hash, this is the code I used:

%json = %{decode_json @lines};
my $result = "keys => { \n";
for my $key (keys %json) {
$result .= "$key\n";
}
$result .= " }\n\n";

print $result;


After execution, I got all the keys displayed but with different order. I got stuck at that point.

Is there any possibility to save the keys order?

Your help will be much appreciated.

Thanks.

Answer

You could create a list (which would be ordered) and in each list element put another list with 2 fields (key and value). That is effectively an ordered hash.

#!/usr/bin/perl

%json = qw(key1 value1 key2 value2 key3 value3);
my $result = "keys => { \n";
for my $key (keys %json) {
  $result .= "$key\n";
}
$result .= " }\n\n";

print $result;

my $json=[];
for my $key (sort keys %json) {
    my @list = ();
    push(@list,$key);
    push(@list,$json{$key});
    push(@$json,\@list);
}

for (@$json) {
    print $_->[0], " ", $_->[1], "\n";
}