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

Is it possible to do something like the following....
#!/usr/bin/perl $dataline = "This is a line of data ISOLATION"; $regex = "m/ISOLATION/"; if ($dataline ~= $regex) { print "Found a match!\n"; } else { print "No match!\n"; }
I need to be able to test against a regular expression stored in a variable...

Replies are listed 'Best First'.
Re: Regex from a variable...
by Masem (Monsignor) on Jun 15, 2001 at 23:52 UTC
    Close, you want to define $regex using the qr perlop operator, as in:
    $regex = qr/ISOLATION/;
    You can then check for a match via what you have there.
    Dr. Michael K. Neylon - mneylon-pm@masemware.com || "You've left the lens cap of your mind on again, Pinky" - The Brain
      It works.... Exactly what I was looking for... Thanks for the response... You guys / gals are super fast!
Re: Regex from a variable...
by nysus (Parson) on Jun 15, 2001 at 23:49 UTC
    No. You would simple do the following:

    $regex = "ISOLATION"; if ($dataline =~ m/$regex/"; print "Found a match!\n"; } else { print "No match!\n"; }
    Update: Watch my typos there. 2nd line should read if ($dateline =~ m/$regex/) {

    $PM = "Perl Monk's";
    $MCF = "Most Clueless Friar Abbot";
    $nysus = $PM . $MCF;

Re: Regex from a variable...
by John M. Dlugosz (Monsignor) on Jun 16, 2001 at 01:20 UTC
    When interpolating a variable into a RE, watch for special chars! Always use \Q...\E to get around that. This has bit me more than once.
    $dataline =~ /\Q$variable\E/
      Overzealous use of an idiom is so wrong as not using it. In this instance he wanted the special chars stay special chars. So don't do this!
Re: Regex from a variable...
by I0 (Priest) on Jun 15, 2001 at 23:52 UTC
    $regex = "ISOLATION"; if ($dataline =~ $regex) { print "Found a match!\n"; } else { print "No match!\n"; }