-1

I have a text file as below and saved it as "file.txt"

"create variable $VAR alarm_object 0"

I am trying to read this in a perl script and printing it by substituting the "$VAR" variable

$VAR = TEMP_VAR
open (FILE,"<", "file.txt") or die $!;
        while (<FILE>) {
                chomp;
                eval(print "$_\n");
        }
        close (FILE);

I need the output as

"create variable TEMP_VAR alarm_object 0"

I tried to achieve this using eval function. It is not working as expected.

How can i achieve this in perl?

Mohan
  • 463
  • 3
  • 11
  • 24

1 Answers1

2

eval is too heavy of a tool for this job. Instead, just use a simple search and replace.

This basically substitutes '$VAR' with $sub for every line of your input file:

use strict;
use warnings;
use autodie;

my $sub = 'TEMP_VAR';

open my $fh, '<', 'file.txt';

while (<$fh>){
    print;             # Before
    s/\$VAR\b/$sub/g;
    print;             # After
}

Outputs:

"create variable $VAR alarm_object 0"
"create variable TEMP_VAR alarm_object 0"
Miller
  • 34,962
  • 4
  • 39
  • 60
fugu
  • 6,417
  • 5
  • 40
  • 75
  • Nor the while loop, seeing as it's just one line. But this way is a safer, more scalable approach, no? – fugu Aug 05 '14 at 18:07
  • Its working as mentioned above. File contains number of such Dollar Variables so while loop is required. correct? – Mohan Aug 06 '14 at 02:28