in reply to Fast lookup for prefixes in hash
Update: Added slight optimization. We are still occasionally repeating the last regex, that's ok though. I don't think there's an optimal way to eliminate it (or I just don't feel liking looking for it at the moment :).my @array = sort keys %hash; # Keep another array for regexps my @regexes = map qr/^$_/, @array; for my $ph_num (@phone_numbers) { my $num = search($ph_num) || 'not'; print "$ph_num $num found\n" } sub search { my $num = shift; my ($start, $end) = (0, $#array); while ($start < $end) { my $mid = ($start+$end)/2; if ($array[$mid] le $num) { return $hash{$array[$mid]} if $num =~ $regexes[$mid]; $start = $mid+1; } else { $end = $mid-1; } } $num =~ $regexes[$start] && $hash{$array[$start]}; }
|
|---|