http://www.perlmonks.org?node_id=931368


in reply to How would I write this multiple substitution script?

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.