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

I initialized a variable and then I parse a text file which includes this variable, while I print this line it is not substitute, means:

for example: 1. Input file: My name is $str1 I live in $str2 I like to eat $str1 2. Perl script #! /usr/local/bin/perl $str1 = "MIKE"; open(DB,"list.txt") || die "ERR: failed to open DB\n"; @all_lines = <DB>; close(DB); @found = grep(/^My/,@all_lines); print @found,"\n"; #######################

Here I see the the line is printed but not substituted with my initialzed $str1 val. Any idea I it can smoothly resolved ?

Thanks
azaria

Replies are listed 'Best First'.
Re: substitue variables from file
by bart (Canon) on Oct 29, 2005 at 21:32 UTC
    There's a module String::Interpolate, but I know of noone who's actually using it.

    There's also some trick using eval or related (s///ee), but that could cause more trouble than it solves: it's quite errorprone and, worse, a snakepit of security holes.

    It really seems to me like you're trying to create a templating system. There's a very good intro articles on templating systems in Choosing a Templating System. Read that first, and see if you still want to go this route.

      Hi Bart, The reference article you sent resolved the problem with the s/\$(\w+)/${$1}/g Many thanks !!! azaria
        You don't want to do that. Look up "symbolic references" or "soft references" for more information as to why. For one thing, they won't do variables that have been declared with my, as you would usually do under strictures.

        Much better is to have a hash that contains all the variable names you wish your file to be allowed to used. Then, you would do s/\$(\w+)/$hash{$1}/g;


        My criteria for good software:
        1. Does it work?
        2. Can someone else come in, make a change, and be reasonably certain no bugs were introduced?