Skip to content

Instantly share code, notes, and snippets.

@karenetheridge
Created March 29, 2013 19:06
Show Gist options
  • Save karenetheridge/5272888 to your computer and use it in GitHub Desktop.
Save karenetheridge/5272888 to your computer and use it in GitHub Desktop.
randomized hash ordering in 17.10, but preservation of order for certain operations
use strict;
use warnings;
my (%hash1, %hash2);
{
my @keys = (0..25);
my @vals = ('a'..'z');
@hash1{@keys} = @vals;
@hash2{@keys} = @vals;
}
# two hashes with identical contents will return a consistent keys order, but
# distinct from each other.
print "keys (random order in 17.10):\n";
print "hash1: ", join(', ', map{sprintf "%2d",$_}keys(%hash1)), ' --- ',
"hash2: ", join(', ', map{sprintf "%2d",$_}keys(%hash2)), "\n" for 1..10;
# assigning one hash to another does not preserve the keys order either.
my %hash3 = %hash1;
print "hash3: ", join(', ', map{sprintf "%2d",$_}keys(%hash3)), "\n";
print "\nremoving keys from the end (as viewed from keys()) preserves order...\n";
print "hash3: ", join(', ', map{sprintf "%2d",$_}keys(%hash3)), "\n";
for (0..25)
{
my @keys3 = keys(%hash3);
delete $hash3{$keys3[-1]};
print "hash3: ", join(', ', map{sprintf "%2d",$_}keys(%hash3)), "\n";
}
print "\n...as does removing keys in the order returned by keys():\n";
print "hash2: ", join(', ', map{sprintf "%2d",$_}keys(%hash2)), "\n";
foreach my $key (keys %hash2)
{
delete $hash2{$key};
print "hash2: ", join(', ', map{sprintf "%2d",$_}keys(%hash2)), "\n";
}
print "\n...as does removing the latest key returned by each(), even if it's not the
last key from keys()'s point of view.
Notice from the output that the order of the keys' removal doesn't even
match what keys() originally returned.\n";
for my $length (reverse (0..25))
{
# stop at a random place in the remaining hash
my $rand = int(rand($length));
my ($key, $val);
for my $i (0..$rand) {
($key, $val) = each(%hash1)
}
# removing key from the middle of the hash is fine, as long as it was the
# last one reported by a call to each()
delete $hash1{$key};
print "hash1: ", join(', ', map{sprintf "%2d",$_}keys(%hash1)), "\n";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment