in reply to regex matching specific strings.

You could use the anchors ^ and $ (Regular Expressions) to force your string to match at beginning and ending of the string respectively. So your code could look something like:

$var =~ /^(?:(?:abc)|(?:def)|(?:ghi))$/;

Regarding skipping regular expressions entirely, since you are testing literal equality, it may make more sense from a maintenance perspective to just test equality with a set of or clauses (perlop):

if ($var eq 'abc' or $var eq 'def' or $var eq 'ghi') { ..code..}

Update: Fixed code, as per ikegami's post below

Replies are listed 'Best First'.
Re^2: regex matching specific strings.
by ikegami (Patriarch) on Jul 22, 2009 at 23:07 UTC

    $var =~ /^(?:abc)|(?:def)|(?:ghi)$/; is wrong. It matches strings that

    • start with "abc"
    • contain "def",
    • end with "ghi", or
    • end with "ghi\n"

    You want

    $var =~ /^(?:abc|def|ghi)\z/;

      My only tiny quibble with that regex, correct as it is, is that using ^ in combination with \z might be confusing to a future reader. I'd suggest:

      $var =~ /\A(?:abc|def|ghi)\z/;

      Which is technically exactly the same as ikegami's suggestion, but points out to the reader "Hey I'm using less-common techniques in this regex" right at the beginning with that \A.

        That is funny, because every single character in a regex could be critical, so unless you know exact meaning of every single character, you should be very very careful :)