This has the added benefit of allowing you to specify more specific mappings that take precedence over more generic. Another possibility might be constructing a tree of sorts, and walking the tree for each digit in your number:sub find_result { my $number = shift; my $prefix_length = length($number); my $result; 1 until defined($result = $hash{substr($number, 0, $prefix_length-- +)}) or $prefix_length <= 0; return $result; }
Creating this new tree-shaped %hash from a list of prefix => result pairs is an exercise for the reader.%hash = ( 1 => { 2 => { 3 => 1, 4 => 2, }, 3 => { 2 => 3, } } ); # Equivalent to ( 123 => 1, 124 => 2, 132 => 3 ) sub find_result { my $number = shift; my $position = 0; my $pointer = \%hash; while (defined(my $current = substr($number, $position++, 1))) { return $current unless ref($pointer->{$current}); $pointer = $pointer->{$current}; } return; }
In reply to Re: Fast lookup for prefixes in hash
by Fastolfe
in thread Fast lookup for prefixes in hash
by Marcello
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |