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

Assume you've got the following code:

#!/usr/bin/perl -w $ID="1234"; open(FILE,"<file.txt"); while(<FILE>) { print; close(FILE); exit 0;
And the file "file.txt" contains:

This is a text file. My ID number is $ID.

When printing out that line, it prints out '$ID' instead of evaluating the variable. How to get the variable to be evaluated? This is eluding me for some reason.

Replies are listed 'Best First'.
Re: Eval'ed data loaded from a file?
by chromatic (Archbishop) on Dec 28, 2000 at 01:46 UTC
    There are at three options. First, write a regex that scans your text for variables, replacing them with the values. It's much, much easier to use a hash for this:
    my $text = "Insert $id here!\n"; my %values = ( id => 10 ); $text =~ s/\$(\w+)\b/$values{$1}/g; print $text, "\n";
    That's untested, but can't be too far off. This is a simple solution that works for simple problems. It's possible to craft a much nicer regex to catch boundary conditions, but it's difficult.

    The second option is an awful abuse of eval I like to call Double Interpolation of a String . I wouldn't recommend it, if you can avoid it.

    The third option is to use a templating mechanism from the CPAN, like Text::Interpolate or Text::Template. This is by far the most powerful and safe mechanism. If you're going to be doing this often, time invested in learning one of these modules will pay off nicely.

      Much abliged.

      I was hoping that there was some stupidly simple explaination but I was expecting something like the above.

      Again, thanks for your time.

Re: Eval'ed data loaded from a file?
by chipmunk (Parson) on Dec 28, 2000 at 01:48 UTC