moked has asked for the wisdom of the Perl Monks concerning the following question:

I'd like perl to replace $variables in a file. The vars are simply listed as $a, $a+50, $b etc in a file, which I read. I use the following:
$a=1; $b=2; .... while ($line = <INFILE>) { chomp($line); # contains $a, $b print "$line\n"; #prints "$a" "$b"
However, perl ignores all the $variables and print them explicitly. How do I make perl specify the variable value when prining $line?

Thx,

Replies are listed 'Best First'.
Re: Making perl evaluate a variable with a string
by jwkrahn (Abbot) on Apr 01, 2007 at 15:34 UTC
Re: Making perl evaluate a variable with a string
by shmem (Chancellor) on Apr 01, 2007 at 15:35 UTC
    What do you expect your code
    $a=1; $b=2; .... while ($line = &lt;INFILE>) { chomp($line); # contains $a, $b print "$line\n"; #prints "$a" "$b"
    to do? Please provide a sample of the output you're trying to get.

    It's not clear what you are trying to achieve. See I know what I mean. Why don't you?

    If you read text to print it later, you print text. If you want to replace text (eg. "$a" with "1"), do so with s/\$a/1/ - see perlre.

    If you want perl to evaluate the file, say so with eval, do or require. Evaluating a file whilst reading it linewise is tricky and outright impossible if those lines aren't self-contained perl statements (e.g. if the file contains control structures spanning several lines).

    --shmem

    _($_=" "x(1<<5)."?\n".q·/)Oo.  G°\        /
                                  /\_¯/(q    /
    ----------------------------  \__(m.====·.(_("always off the crowd"))."·
    ");sub _{s./.($e="'Itrs `mnsgdq Gdbj O`qkdq")=~y/"-y/#-z/;$e.e && print}
      Hi again I have a template script for another tool. from the template I want generate many scripts with different numerical values (not only replace $a with 1, but also replace in the template script, $a+5 with 6...) So, I have a template script and a variable definintion file which I call with "require" How best to implement? Sure I can do it with =~s/.../ but if I can use perl to make the sub in a native manner ($var) it will be much stronger. Thx, Nir
Re: Making perl evaluate a variable with a string
by Anonymous Monk on Apr 02, 2007 at 02:57 UTC
    Since '$line' is a variable, the compiler doesn't know what it contains : variable names, prayers, profanity, ... . You want your program to evaluate the contents of $line as Perl code. Look up the 'eval' function. Hope this helps.