in reply to matching a regular expression

You can use index to good effect like this:

use strict; use warnings; my $state; my $firstAttempt = 1; while (1) { if($firstAttempt) { $state = promptUser("What network to listen for SNMP traps [hs +bn or admin]? ", "admin"); ; $firstAttempt = 0; } else { $state = lc promptUser("ERROR: $state Invalid Re-enter the net +work"); } if (0 == index 'hsbn', $state) { $state = 'hsbn'; last; } elsif (0 == index 'admin', $state) { $state = 'admin'; last; } } if ($state eq 'hsbn') { #some action }

Note that if you need to disambiguate between two strings that match for the first few characters you can require some number of characters thus:

if (0 == index 'hsbn', $state and length ($state) >= 2) {

DWIM is Perl's answer to Gödel

Replies are listed 'Best First'.
Re^2: matching a regular expression
by blazar (Canon) on May 18, 2006 at 10:57 UTC
    Note that if you need to disambiguate between two strings that match for the first few characters you can require some number of characters thus:

    Or else one may proceed like thus:

    my @matching=grep { 0 == index $_, $userinput } @commands;

    Then take actions according to whether @matching==0, @matching==1 or @matching>=2. In the latter case depending on what the commands are actually supposed to do I would either emit a warning and decide upon priority (which may be given by the ordering of @commands itself) or ask the users to refine their input.

    Update: minimal example follows.

    #!/usr/bin/perl use strict; use warnings; my @commands=qw/foo bar baz/; print "Choose command [@commands]\n"; { chomp(my $cmd=<STDIN>); my @ok=grep { 0 == index $_, $cmd } @commands; print "You chose [@ok]\n" and last if @ok==1; warn +(@ok>1 ? "Ambiguos command [@ok]" : "Invalid command"), ", retry!\n"; redo; } __END__

    Usage example:

    $ ./foo.pl Choose command [foo bar baz] fred Invalid command, retry! fo You chose [foo] $ ./foo.pl Choose command [foo bar baz] ba Ambiguos command [bar baz], retry! bar You chose [bar]