I know how to add new elements to the hash, but I need to prioritise the new elements and print them first.
I found that, the hash printed will follow the sequence itself, not print randomly, and I know that when I add a new one, it will appear directly on the bottom. Is there any way to add new elements directly on the top of the hash?
or after adding new elements, and they can be shown first? (all the elements in the hash will be displayed but the new will be on top)
CodePudding user response:
No. Hashes are unordered in Perl. If you have observed that keys seem to come out in a particular order that is a coincidence. You cannot rely on them always coming out in that order.
There are ways you can prevent this native behaviour of Perl, but it's not a good idea to do so. If you want order, you need an array. You can store the keys of the hash in an array to preserve the order that you like. For example:
$hash{$key} = $foo;
push @keys, $key; # store key in array
In this array, the new keys will be at the end, so to get the newest key you would do:
my $newest = pop @keys; # get newest key
CodePudding user response:
There's at least one module on CPAN, Tie::IxHash, that provides ordered array-like access and hash-like random lookup by key:
This Perl module implements Perl hashes that preserve the order in which the hash elements were added. The order is not affected when values corresponding to existing keys in the IxHash are changed. The elements can also be set to any arbitrary supplied order. The familiar perl array operations can also be performed on the IxHash.
Example script:
#!/usr/bin/env perl
use strict;
use warnings;
use feature qw/say/;
use Tie::IxHash;
my $t = tie my %hash, 'Tie::IxHash', a => 1, b => 2, c => 3;
$hash{'last'} = 4; # Will appear at the end of the elements
$t->Unshift(first => 0); # Will appear at the beginning of the elements
while (my ($k, $v) = each %hash) {
say "$k: $v";
}
and output:
first: 0
a: 1
b: 2
c: 3
last: 4