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
In reply to Run a variable as a line of code? by lev36
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |