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

Hola Monks!

I want to save a regex in a config file (user editable)
then apply it in my program. (It will be used by only ONE person, so I am less concerned about causing problems, but maybe should be???)

I can get this to work: (where $regex is read from file)
if ($txt =~ m/$regex/) { blah...blah...blah }

But then the config file needs to worry about the delimited character of the regex or no delimiter means embedded spaces (esp. trailing) are hard to "see"

I would like to do:
if ($txt =~ $regex){ blah...blah...blah }
but it doesn't work...

I have been looking into eval, but if it can work, I
haven't figured it out ;)

Any ideas?

thanks,
-john

Replies are listed 'Best First'.
Re: outside user defined regex
by chipmunk (Parson) on Sep 17, 2001 at 07:21 UTC
    $txt =~ m/$regex/ and $txt =~ $regex are in fact equivalent. They apply the regex stored in $regex in exactly the same way.

    With the first snippet, you do not need to worry about the delimiter appearing in $regex, because the trailing delimiter is found before $regex is interpolated.

    If you really want to use delimiters around the regex in the config file, you can, but you'll want to remove them before applying the regex. Here's an example.

    my $regex = <DATA>; chomp($regex); $regex =~ s,^/,,; $regex =~ s,/$,,; my $txt = "The target string."; if ($txt =~ m/$regex/) { print "Yes.\n"; } if ($txt =~ $regex) { print "Yes.\n"; } __DATA__ /\bt\w+t\b/
Re: outside user defined regex
by smackdab (Pilgrim) on Sep 17, 2001 at 10:02 UTC
    Thanks, was so caught up in the eval thing...didn't even think about blasting the 'm/' and '/'...
    This allows the user to use any delimiter, which is good.
    And I learned that Perl *knows* that a regex follows '=~'
    ;)