Return a Random Hash inside a Hash of Hashes or a Random Hash Key
The following will return a random key from the top level hash (in this case foo
or bar
) which is then used to grab a value from the second level hash:
my %hash = (
foo => { x => "0", y => "1" },
bar => { x => "2", y => "3" }
);
print $hash # reference to the top level hash
{[keys %hash]-> # get an array of the top level hash's keys
[int(rand($#{[keys %hash]}+0.5))]} # generate a random number based on the number of elements in the top level hash, thereby selecting a random top level hash key
{x}; # key for second level hash under random first level key
And if you just want a random hash key for use elsewhere:
print [keys %hash]-> # get an array of the top level hash's keys
[int(rand($#{[keys %hash]}+0.5))]; # generate a random number based on the number of elements in the top level hash, thereby selecting a random top level hash key