NAME
Array::Lookup - Lookup strings in arrays or hash tables with abbreviation.
SYNOPSIS
use Array::Lookup;
$value = lookup $key, \@keywords, \¬found, \&toomany;
$value = lookup $key, \%keywords, \¬found, \&toomany;
lookup_error $key, $keywords, $err, $msg;
DESCRIPTION
lookup
Lookup $key
in the table @keywords
and return the unambiguously matching keyword, if any. If the second argument is given as a hash array, %keywords
, then lookup a matching key, with abbreviation, and return the value corresponding to the unambiguously matching key.
If there are no matches, invoke ¬found
like this:
&$notfound( $key, \@keywords, '');
If there are two or more matches, invoke &toomany
like this:
&$toomany( $key, \@keywords, \@matches);
If either subroutine is omitted or null, then no special action is taken except that undef
is returned for the failed lookup.
Note that the third argument, the array of ambiguous matches, allows a common subroutine to be used for both error conditions and still distinguish the error.
See "lookup_error" for a standard method of handling lookup failures.
lookup_error
Handle an error for the lookup
subroutine. The arguments:
- $key
-
The search key which failed the lookup.
- $keywords
-
The hash or array reference containing the keywords none of which matched the
$key
. - $err
-
A flag indicating if the lookup failed because of no matches at all (''), or if the lookup failed because of too many matches (
\@matches
); - $msg
-
A format string used to format and print the error message. It should contain two printf substitution sequences:
%s
. The first will be substituted with the failed lookup key; the second with one of the phrases:"not found"
or"is ambiguous"
, depending upon$err
.If
$msg
is omitted or null, a default message will be used:"lookup failed: %s %s; use one of:\n"
followed by a listing of the strings in the
$keywords
array.
EXAMPLES
Using arrays
use Array::Lookup;
...
@keywords = qw(quit find get set show);
...
$command = <STDIN>;
$command = lookup $command, \@keywords,
sub { lookup_error @_, "Unknown command '%s'; use one of:\n"; },
sub { lookup_error @_, "Command '%s' %s; use one of:\n"; };
Using hashes
use Array::Lookup;
...
%Commands = ( 'quit' => \&quit, 'get' => \&get, 'set' => \&set,
'find' => \&find, 'show' => \&show );
...
$input = <STDIN>;
$command_sub = lookup $input, \%Commands,
sub { lookup_error @_, "Unknown command '%s'; use one of:\n"; },
sub { lookup_error @_, "Command '%s' %s; use one of:\n"; };
SEE ALSO
AUTHOR
Alan K. Stebbens <aks@sgi.com>