# sub weighted_hash # chooses and returns a random key from a hash; # the probability of choosing a specific key # is weighted by the value associated with that key sub weighted_hash{ my $hashref = shift; my %hash = $$hashref; my @weighted; foreach my $key (keys %hash){ my $weight = $hash{$key}; while ($weight >0){ push @weighted $key; $weight--; } } rand_elt @weighted; }