user2013387
user2013387

Reputation: 203

Variable replacement using regex

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?

Upvotes: 3

Views: 62

Answers (1)

toolic
toolic

Reputation: 61987

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??

Upvotes: 3

Related Questions