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 :)
|