Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?
 
PerlMonks  

Re: How would I write this multiple substitution script?

by TomDLux (Vicar)
on Oct 13, 2011 at 19:35 UTC ( #931368=note: print w/ replies, xml ) Need Help??


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.


Comment on Re: How would I write this multiple substitution script?
Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://931368]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others musing on the Monastery: (9)
As of 2015-07-06 16:31 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (77 votes), past polls