in reply to matching a regular expression
You'll have to do more work if you want to print a list of commands that matched the ambiguous action they've entered. In which case you'll probably just want to avoid Text::Abbrev altogether and roll your own solution.use Text::Abbrev; use strict; print "Enter a command: "; chomp(my $action = <STDIN>); # they could enter 'adm' or 'h' my %modes = abbrev(qw( hsbn admin ... )); # if $modes{$action} is defined, that means it is a # NON-AMBIGUOUS abbreviation of 'hsbn', 'admin', etc. if (defined(my $fullaction = $modes{$action})) { if ($fullaction eq 'hsbn') { ... } elsif ($fullaction eq 'admin') { ... } ... } else { print "$action was ambiguous.\n"; }
Which reminds me: I think I saw this in the Perl Cookbook... if you reverse the arguments of the pattern match, you can get the desired effect:
Update (8:30 AM EDT): I just figured out a nifty way to do abbreviation matching and ambiguity reporting at the same time, with a regex, of course.if ("hsbn" =~ /^$action/) { # $action is "h", "hs", "hsb", or "hsbn" }
I think it's pretty clever. $valid is a string with newlines between every complete action name: "hsbn\nadmin\nhelp\nquit". The regex /^($action.*)/mg does a few things. First, the /m modifier means that the ^ in the regex matches at the beginning of the string OR after any internal newline. The ($action.*) part matches not only the abbreviation the user entered, but also the rest of the non-newline characters after it (i.e. the completion of the action name). The /g modifier returns all matches found, so that if they only entered 'h', you'd get back ("hsbn", "help"). I hope that's helpful for you.my $valid = join "\n", qw( hsbn admin help quit ... ); chomp(my $action = <STDIN>); my @matches = $valid =~ /^($action.*)/mg; if (@matches == 0) { print "No command matched '$action'\n"; } elsif (@matches > 1) { print "Multiple commands matched '$action': [@matches]\n"; } else { print "You selected $matches[0].\n"; }
UPDATE (9:30 PM EDT): Text::Abbreviate, coming to a CPAN mirror near you...
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: matching a regular expression
by pileofrogs (Priest) on May 18, 2006 at 23:36 UTC |