Perl: How to read text from file and process $variable in that data too.

In the hello.htm have the sentenses:

Hello $name 
How are you?

The perl script:

$name = "David";

open(HEADER,"hello.htm");
while(<HEADER>) { $html .= $_; }
close(HEADER);

print "$html";

I making something about template. But it can't process the $name variable.

Here i am substitute the name after "hello" found.
i modifier in pattern matching denotes ignore case.
s denotes sunstitution
g denotes global.

Cheers,
Ranga:)

1 Like

Good idea. Use search and replace. No other solution?

$name = "David";

open(HEADER,'hello.htm');
while(<HEADER>) { $_ =~ s/\$name/$name/g; $html .= $_; }
close(HEADER);

print "$html";

You can do in various ways, But search and replace is the better way i think,

 
$_ =~ s/\$(\w+)/${$1}/g;    #I don't know why didn't work
$_ =~ s/(\$\w+)/$1/eeg;     #Work!

These can replace any variables. Thanks!