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


in reply to Apply A Set Of Regexes To A String

If the regexen are mutually exclusive (ie, they do not affect the same things), then perhaps something along the lines of the following:

my %regexen = ( '*' => [ { 'replace' => qr/blah/, 'with' => 'duh' }, { 'replace' => qr/baz/, 'with' => 'quuz' }, { 'replace' => qr/(b)ar/, 'with' => '$1um' } ], 'cgi-bin' => [ { 'replace' => qr!usr/local/bin/perl!, 'with' => 'usr/bin/perl' } ] ); foreach my $directory ( '*', 'cgi-bin' ) { foreach my $file ( glob("$directory/*") ) { next if ( $file =~ m/\.(jpg|png|gif|zip|gz|jar|pl|bak|\~)$/i ); print "Processing... $file (old file as ${file}.bak\n"; open( INF, $file ) or die("Can't open $file for input: $!\n"); open( OUTF, '>' . $file . '.new' ) or die("Can't open $file.new for output: $!\n"); binmode(INF); binmode(OUTF); while ( my $line = <INF> ) { foreach my $rx ( @{ $regexen{$directory} } ) { $line =~ s/$rx->{'replace'}/$rx->{'with'}/; } print OUTF $line; } close(INF); close(OUTF); rename( $file, $file . '.bak' ); rename( $file . '.new', $file ); } }

This would loop thru a directory at a time, making changes to each file (and saving the original with a .bak extension). The only problem with the code above is if the modifications affect the same things, in which case if all modifications affect all files, you would add them under the '*' set, otherwise you would have to add them to the set for each of the directories (or files, if you need to break it down in that way).

I'm not sure if this is necessarily the best way, but it is an idea. Hope it helps.