in reply to Switch/Format to not interpret metacharacters in regex?

If what you really want to do is just look for one string in another than index is the better tool:

use strict; use warnings; my $match = "Tick F***ing Tock"; my $str = "Friday night at 11:30pm the start of a new series, 'Tick F* +**ing Tock' explores..."; if (-1 != index $str, $match) { print "..do something..\n"; }

If you really want to use a regex then use quotemeta to do the quoting for you:

use strict; use warnings; my $match = "Tick F***ing Tock"; my $str = "Friday night at 11:30pm the start of a new series, 'Tick F* +**ing Tock' explores..."; $match = quotemeta $match; if ($str =~ $match) { print "..do something..\n"; }
Optimising for fewest key strokes only makes sense transmitting to Pluto or beyond

Replies are listed 'Best First'.
Re^2: Switch/Format to not interpret metacharacters in regex?
by mis (Initiate) on Dec 04, 2019 at 02:09 UTC
    I'm actually fixing someone elses code, based on the actual code the fix might be as simple as:
    if (lc($b) eq lc($a)) { print "do something...\n"; }
    However the first answer (using /\Q$a\E/) has immediately fixed the issue and knowing the data it will be a permanent fix for the issue... it also taught me something that I probably have come across in the past... 20+years working with perl and I still learn something new every so often... :)

    Thanks, all.

      G'day mis,

      Welcome to the Monastery.

      Two quick points:

      • $a and $b are special variables which I'd recommend avoiding except for their special purposes. See perlvar: $a for more information.
      • Instead of using lc (or uc) consider fc. Note that you'll need Perl 5.16 for that.

      — Ken