Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

Re: string replacement

by huck (Vicar)
on Sep 12, 2017 at 15:31 UTC ( #1199209=note: print w/replies, xml ) Need Help??


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.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1199209]
help
Chatterbox?
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others surveying the Monastery: (6)
As of 2017-10-20 09:38 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    My fridge is mostly full of:

















    Results (260 votes). Check out past polls.

    Notices?