in reply to surprised to find cannot assign s/../../ to a variable
is short for$a =~ $b
$a =~ m/$b/;
There's no reason to expect any of the following to evaluate the Perl code found in $b:
$p = '4+5*6'; $str =~ m/$p/; # Doesn't perform arithmetic. $p = 'm/a/'; $str =~ m/$p/; # Doesn't search for `a`. $p = 's/a/b/'; $str =~ m/$p/; # Doesn't perform a substitution.
Same:
$p = '4+5*6'; $str =~ $p; # Doesn't perform arithmetic. $p = 'm/a/'; $str =~ $p; # Doesn't search for `a`. $p = 's/a/b/'; $str =~ $p; # Doesn't perform a substitution.
qr// compiles a regular expression, not Perl code. It doesn't help at all here.
$p = '4+5*6'; $re = qr/$p/; $str =~ m/$re/; # Still doesn't. $p = 'm/a/'; $re = qr/$p/; $str =~ m/$re/; # Still doesn't. $p = 's/a/b/'; $re = qr/$p/; $str =~ m/$re/; # Still doesn't.
Same:
$p = '4+5*6'; $re = qr/$p/; $str =~ $re; # Still doesn't. $p = 'm/a/'; $re = qr/$p/; $str =~ $re; # Still doesn't. $p = 's/a/b/'; $re = qr/$p/; $str =~ $re; # Still doesn't.
have to write like this
Yes, if you have Perl code you wish to compile and run, you will need to pass it to eval EXPR, do, require, use, or to the perl program itself.
I used to think qr take care of all regex expressions
You're not trying to "take care of a regex expression", whatever that means. You are trying to perform a substitution. That requires the use of the substitution operator (s///), but you used a match operator (m//) in your broken code.
qr// compiles a regular expression. That's it. It doesn't perform any matches or substitutions. To perform matches or substitutions, you still need Perl code that uses the match operator (m//) or the substitution operator (s///).
Proper use:
my $pat = 'a'; my $re = qr/$pat/; $str =~ m/$re/ # Performs a match. $str =~ /$re/ # Same $str =~ $re # Same $str =~ m/$pat/ # No need to compile in advance. $str =~ /$pat/ # Same $str =~ $pat # Same
my $pat = 'a'; my $repl = 'b'; my $re = qr/$pat/; $str =~ s/$re/$repl/ # Performs a substitution. $str =~ s/$pat/$repl/ # No need to compile in advance.
Use String::Substitution if the replacement string contains $1, etc.
|
|---|