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


in reply to string replacement

This problem is not quite as simple as it seems. There are a number of cpan ways to read a parm file. Lets bypass that for now and focus on the replacement. The replace pairs are already in hashs that are part of an ORDERED array here.

use strict; use warnings; my @reps; push @reps,{from=>'ZZZ',to=>'456AAA456'}; push @reps,{from=>'AAA',to=>'AAA123'}; push @reps,{from=>'BBB',to=>'XYZ999'}; push @reps,{from=>'DEF',to=>'ANYOTHER'}; while (my $line=<DATA>) { chomp $line; for my $rep (@reps){ my $from=$rep->{from}; my $to =$rep->{to}; $line=~s/\Q$from\E/$to/g; } # rep print $line."\n"; } # line __DATA__ AAAA more stuff stuff BBB again DEF stuff |ZZZZ| not as simple as it seems
Result
AAA123A more stuff stuff XYZ999 again ANYOTHER stuff |456AAA123456Z| not as simple as it seems
As you can see, if a "to" contains a "from" the order of execution is important. There is a lot that could be improved here, pre-compiling the regexp parts for instance, but this is a simple demo of how it can be done and one of the pitfalls.