in reply to qr and substitution

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

Replies are listed 'Best First'.
Re^2: qr and substitution
by Aristotle (Chancellor) on Oct 13, 2003 at 19:04 UTC
    If you do it this way, you have to be very careful with the contents of $re - you have a quoting context in the s/// which is defined within a quoting context, so for s!\\!/!g you'd have to pass 's!\\\\!/!g'. It's much easier to screw up this way than by passing a subref or a compiled RE and a string to eval in the right side of an s///ee;.

    Makeshifts last the longest.