Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable replacement using regex

Tags:

regex

perl

I want to replace a variable in a file (temp.txt) in Perl.

temp.txt

Hi  $test. How are you??

I want to replace the variable $test together with it's value. I want to replace the string $test in a file with abc. This is the code I tried:

open my $filename, "<", temp.txt or die $!;

while (<$filename>) 
{ 
   s/$test/'abc'/g;
   print;
}   

It is not working. Can anyone tell me what am I doing wrong?

like image 277
user2013387 Avatar asked Jul 02 '26 02:07

user2013387


1 Answers

You need to escape the $ because Perl thinks $test is a variable:

use warnings;
use strict;

while (<DATA>) {
    s/\$test/'abc'/g;
    print;
}

__DATA__
Hi  $test. How are you??
like image 81
toolic Avatar answered Jul 05 '26 04:07

toolic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!