lev36 has asked for the wisdom of the Perl Monks concerning the following question:
I have a little script that iterates through a list of files and makes a substitution to lines matching a pattern. It writes the new version of the file over the old, after having saved the old with a .bak extension.
Here's the part that actually does the substitution:
#earlier in the script, we have created #the array of files to edit, and named it @files foreach my $filename (@files) { my $backup = $filename . '.bak'; copy($filename, $backup) unless -e $backup; open(FILE2CHANGE, "<$backup"); open(UPDATED, ">$filename") or die "$filename: $!"; while (<FILE2CHANGE>) { s/foo/bar/g; print UPDATED; } close FILE2CHANGE; close UPDATED; }
To make this script more reusable, I would like to remove the substitution line (s/foo/bar/g) and, instead, have the script read one or more substitution commands from a separate file.
To wit, the substitution file might read:
s/foo/bar/g s/something/something else/
In which case, the script would read these lines and execute them both, upon each file. But I don't want this substitution file to be an executable script in itself; just a data file containing the lines to be used to make the substitution(s).
It's easy enough to read these lines into a array, but is there a way to then run the lines from the variable as if they were lines of code?
Of course, in an ideal world, the script should first make sure the substitution commands look valid, but I haven't even tried to wrap my head around that problem yet...
Thanks,
Lev
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Run a variable as a line of code?
by Zaxo (Archbishop) on Apr 03, 2006 at 21:13 UTC | |
|
Re: Run a variable as a line of code?
by CountZero (Bishop) on Apr 03, 2006 at 21:30 UTC | |
by hardburn (Abbot) on Apr 04, 2006 at 16:39 UTC | |
by CountZero (Bishop) on Apr 05, 2006 at 06:15 UTC | |
|
Re: Run a variable as a line of code?
by GrandFather (Saint) on Apr 03, 2006 at 21:16 UTC | |
by QM (Parson) on Apr 03, 2006 at 22:28 UTC | |
by lev36 (Sexton) on Apr 06, 2006 at 17:53 UTC | |
by GrandFather (Saint) on Apr 06, 2006 at 19:26 UTC | |
|
Re: Run a variable as a line of code?
by NetWallah (Canon) on Apr 03, 2006 at 21:27 UTC | |
|
Re: Run a variable as a line of code?
by lev36 (Sexton) on Apr 03, 2006 at 21:50 UTC |