Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
PerlMonks  

Re: How would I write this multiple substitution script?

by TomDLux (Vicar)
on Oct 13, 2011 at 19:35 UTC ( [id://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.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others admiring the Monastery: (4)
As of 2024-04-19 16:51 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found