########################### #from Perl Cookbook 2.10 #take in a hash and via a weighted random, pick one of the #keys based on the value and return it ########################### sub weighted_rand { my %dist = @_; my ($key, $weight); my $rand; while (1) { # to avoid floating point inaccuracies $rand = rand; while ( ($key, $weight) = each %dist ) { return $key if ($rand -= $weight) < 0; } } } ###########################