Of course, if you want the lookup to be faster, use a binary search instead.my $str="17:43:33:21:23:19:27:6"; my %hash=split/:/,$str; my $count; my %ad_lookup; foreach my $k(keys %hash) { $count += $hash{$k}; $ad_lookup{$count} = $k; } my $rand = rand(100); my $adid; foreach ( sort {$a <=> $b} keys %ad_lookup ) { $adid = $ad_lookup{$_} unless defined( $adid); if ( $_ <= $rand ) { $adid = $ad_lookup{$_}; } else { last; } }
-QM
--
Quantum Mechanics: The dreams stuff is made of
In reply to Re: $str to %hash to @ary
by QM
in thread $str to %hash to @ary
by abaxaba
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |