开发者

How do I use a Perl variable in a regular expression?

开发者 https://www.devze.com 2023-01-19 00:02 出处:网络
I am trying to do a search and replace with variables. In this case variables that I pulled from a previous match. Here is my code:

I am trying to do a search and replace with variables. In this case variables that I pulled from a previous match. Here is my code:

$fileContentToAlter =~ s/$2/$1/开发者_Python百科g;

Now I realize in that state, it is being read incorrectly as $ has its own meaning inside of a regexp. I did some searching on the web and read that doublequotes could fix the problem as it would interpolate but that doesn't seen to work for me. I'm not going to lie, this is a homework assignment so I am not expecting a flat out answer. Just a nudge in the right direction.


Avoid '$1' and '$2' because they are regex metacharacters.

use strict;
use warnings;

my $val1 = "abc";
my $val2 = "def";
while (<>)
{
    s/$val1/$val2/g;
    print;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消