
Substituting variables in a text file
Quote:
> Here's the problem: I'd like to substitute words in a text file with their
> counterpart variable in a perl script. (That was horribly phrased, but maybe
> this will help explain...)
[...]
> open (FILE, "filename.txt");
> $printtemp = join ('',<FILE>);
the idiom goes
undef $/; # use a block and local() in stead if you need $/ in other places
$printtemp = <FILE>;
Quote:
> close (FILE);
> $printtemp =~ s#<!-- NAME -->#$NAME#sg;
> [...]
> Anybody have an easier way to open up a file and replace the exact variables
> without having to create variable placeholders and substitute them one at a
> time like I did in the above example?
Yeah - you _could_ look into eval (perldoc -f eval). But I like the
"placeholders" better. eval is generally viewed with a lot of suspicion
since it's generally an indicator of questionable design and can be
pretty dangerous (though of course it's called for in some cases).
I think you should use some kind of markup ($XXX or <%&XXX> or whatever)
and then use a substitution regex to extract the "keyword" and replace
the markup sequence with values that you keep in a hash. Dont let the
variable's names carry semanthics - it's bad design:
#!/usr/bin/perl -w
use strict;
my %symbols = (
NAME => "Albert",
DOG => "Fido",
CAR => "Dodge"
);
undef $/;
my $text = <DATA>; # this can be questioned by the way, but if the file's
# not huge it's OK
$text =~ s/%!([^!]+)!%/$symbols{ $1 }/g;
print $text;
__DATA__
Hello! My name is %!NAME!%, and all I ever do
is walking my dog %!DOG!%. That is unless
I'm out for a spin in my %!CAR!%.
--
Jakob Schmidt
http://aut.dk/orqwood
etc.