ivanatora has asked for the wisdom of the Perl Monks concerning the following question:

I need to check if the value of one variable contains the value of another variable. What I mean:
if ($vord =~ /^$nick$/i){ ...
That works fine, but if $nick contains weird symbols such as "[]" I got error message:
"Unmatched \[ in regex; marked by <-- HERE in m/^Snipe[ <-- HERE Style$/ at..."
I coud do that with: $vord eq $nick, but I want case insensitive search.
Any ideas?

Replies are listed 'Best First'.
Re: If two variables match
by Corion (Patriarch) on Nov 24, 2005 at 20:24 UTC

    There are many ways you could move forward from here:

    1. One way is to convert both values to a unified representation, for example all-upper-case or all-lower-case, and then compare the two with simple string equality:
      if (uc $vord eq uc $nick) { ... }
    2. Another way is to compile your $nick into a safe regular expression and check against that:
      if ($vord =~ /^\Q$nick\E$/i) { ... }
      The \Q .. \E escapes turn of the interpretation of all regular-expression metacharacters in-between them.

      Side note on option 1. English may let you get away with uc'ing to do a comparison. Certain other languages do not. It's just a good I18N habit to get into to always use lower-case to compare. I've never really fully understood this advice from our I18N experts at work, but I take their word for it. Even if that makes me a bit of a cargo-culter. I'm not ashamed to admit it - I'm a unilingual person, so to keep from ticking off our Nordic customers, I'm more than happy to follow this advice. ;-)

      Also, side note on option 2 - I think that option 1 is likely to be significantly faster. Benchmark to be sure.

        If you want to give your language experts a counter example, in German, the "sharp-S" / "eszet" letter "ß", compounded of "s" and "z", has no uppercase equivalent and is always written as "SS" when uppercased. For example straße ("street") becomes STRASSE. If you want to match case-insensitively here, you either have to normalize all ß to "ss" before comparing or you can "normalize" by converting to upper case.

        But I admit that this is some corner case which is unlikely to affect non-Germans :-)

Re: If two variables match
by cog (Parson) on Nov 24, 2005 at 20:21 UTC
Re: If two variables match
by monarch (Priest) on Nov 24, 2005 at 22:38 UTC
    It appears you're watching to see if two variables contain the same data (ignoring case).

    However if you want to see if one variable contains the value of another variable e.g.

    my $vord = "Something Very Long"; my $nick = "Very";
    ..then you probably don't want the anchors in your regular expression..e.g.
    if ( $vord =~ m/\Q$nick\E/i ) { ... }