You want to do a number of substitutions to each file in a directory, with different substitutions for each of a large number of directories.

I would suggest putting the directories and associated substitutions into a data structure. It's a little simpler to put at the top of the file, but harder to modify. Reading in a YAML file containing the rules is a little more complicated to get working, but simpler to maintain over the years, if this is something that will be used for a long time.

Since you're a novice, I'll suggest putting the data in the file:

use autodie; use File::Temp qw(tempfile); my @RULES = ( { dir => '/path/to/dir1', mods => [ 'yellow', 'green' ], [ 'red', 'blue' ] ], }, { dir => '/path/to/dir2', mods => [ [ 'puce', 'chartreuse' ], [ 'lime green', 'ma +genta' ] ], }, ); ... for my $rule ( @RULES ) { chdir $rule->{dir}; for my $file ( glob( .* * ) ) { open my $input, '<', $file; my ($output, $outfile) = tempfile(); while ( my $line = <$input> ) { chomp $line; for my $sub ( @{ $rule->{mods} } ) { $line =~ s/$sub->[0]/$sub->[1]/ } print $output $line; } close $input; close $output; replace_file( $file, $outfile ); } }

I leave for you the process of verifying the old file is successfully replaced by the new file. The regexes will be recompiled on each search-and-replace, but if they are really literal strings, that won't be too expensive. If there were matches, I would suggest precompiling the exporessions, but I'm not sure that works for search-and-replace.

As Occam said: Entia non sunt multiplicanda praeter necessitatem.


In reply to Re: How would I write this multiple substitution script? by TomDLux
in thread How would I write this multiple substitution script? by Carnival

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.