Perhaps this snippet can be made to do what you want.

use strict; use warnings; my $string = "This is a test."; my $re = "s/test/TEST/i"; eval "if( \$string =~ $re ) { print qq/Yep\n/; }"; warn $@ if $@; print $string, "\n";

qr// allows you to pass the meat of a regular expression around compiled within a scalar variable. qr// doesn't allow for the regexp quotish operators to be embedded within (as in qr[s///].... that doesn't work), because it is not intended to contain any kind of code except for the meat of a regexp. If you want to pass a piece of actual code around as though it were a string, the way to execute the string is to eval it.

As Aristotle pointed out, you always have to think carefully when you pass quotes or quote-like operators within a quoted string. But if you ask how to do a tricky thing, you get a tricky solution. ;) eval is never for the faint of heart. As Aristotle points out, it's safer and cleaner to pass a code ref rather than stringified code.


Dave


"If I had my life to do over again, I'd be a plumber." -- Albert Einstein

In reply to Re: qr and substitution by davido
in thread qr and substitution by jplindstrom

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.