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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.