sub choose_weighted { my $weights = shift; my $total = 0; $total += $_ for @$weights; my $rand_val = $total * rand; my $i = -1; $rand_val -= $weights->[++$i] while ($rand_val > 0); return $i; }