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

I'd like to open a file, which will contain some perl variables (e.g. $example), then print out the file, with the variables expanded to their values. I'm guessing this is not anything new... the following code snippet doesnt do it (prints '$example' instead of 'this is an example')... advice?
$example = 'this is an example"; open(FILE, "file")||die("cant open file"); while(<FILE>) { print "$_"; } close(FILE); }

Replies are listed 'Best First'.
Re: Variable expansion in $_
by r0b (Pilgrim) on Jun 11, 2002 at 20:13 UTC
Re: Variable expansion in $_
by smgfc (Monk) on Jun 12, 2002 at 00:28 UTC

    Well, if the variable is on a line by itself then you can just create a hash of variable names with the values of what you want to interpolate. i.e.

    my %hash = ( '$example' => 'This is an example ', '$comment' => 'This is a comment' ); open (FILE, 'file') or die ("Can't open file: $!\n"); while (<FILE>) { chomp; if (exists $hash{$_}) { print $hash{$_}; } else { print $_; } } close (FILE);

    If you plan on putting the variables anywhere in the file, not just on a line by themselves, you just need to to add a foreach loop for the keys of the hash.

    my %hash = ( '$example' => 'This is an example ', '$comment' => 'This is a comment' ); open (FILE, 'file') or die ("Can't open file: $!\n"); while (<FILE>) { chomp; foreach $key (keys %hash) { s/$key/$hash{$key}/g; } print $_; } close (FILE);

    But this only works if you dont have keys in the values i.e.

    my %hash = ( '$example' => '$comment is a variable', '$comment' => 'this is a comment' );

    so don't do that :)

Re: Variable expansion in $_
by zejames (Hermit) on Jun 12, 2002 at 03:45 UTC
    One other way to do it would be the following

    $example = "This is an example"; while(<DATA>) { chomp; s/^\$//; print $$_; } __DATA__ $example

    Of course, when using the method, it would be even simpler if your file contained variable names without the '$', allowing to remove the substitution code line.

    HTH

    -- zejames