$w ) { $sum += $w; # Do not return keys if they have 0 weight. # Note that the "all 0 weight" case is handed above if ( $w > 0 && $sum >= $rand ) { break; } } return $i; } }