Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine

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
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?

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

How do I use this? | Other CB clients
Other Users?
Others scrutinizing the Monastery: (6)
As of 2018-07-18 11:07 GMT
Find Nodes?
    Voting Booth?
    It has been suggested to rename Perl 6 in order to boost its marketing potential. Which name would you prefer?

    Results (389 votes). Check out past polls.