Beefy Boxes and Bandwidth Generously Provided by pair Networks Joe
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

Re: Conditional Search and Replace

by Hue-Bond (Priest)
on May 01, 2010 at 08:53 UTC ( #837914=note: print w/ replies, xml ) Need Help??


in reply to Conditional Search and Replace

This is my take at it:

use warnings; use strict; my @repls = ( [ qr/pat1/, 'repl1' ], [ qr/pat2/, 'repl2' ], [ qr/pat3/, 'repl3' ], ); my $txt = <<'EOF'; This is some example (pat1) text which will be (pat3) modified according (pat2) to some replacement (pat2) rules. EOF foreach my $r (@repls) { $txt =~ s/$r->[0]/$r->[1]/eg; } print $txt; __END__ This is some example (repl1) text which will be (repl3) modified according (repl2) to some replacement (repl2) rules.

If you want to capture things and use them, it gets more (too?) complicated:

use warnings; use strict; my @repls = ( [ qr/pat(\d+)/, 'qq{repl$1}' ], ); my $txt = <<'EOF'; This is some example (pat42) text EOF foreach my $r (@repls) { $txt =~ s/$r->[0]/$r->[1]/eeg; } print $txt; __END__ This is some example (repl42) text

Note the use of qq{} in single quotes and the double eval in the substitution. The first eval turns $r->[1] into qq{repl$1} and the second one turns that into repl42.

--
 David Serrano
 (Please treat my english text just like Perl code, i.e. feel free to notify me of any syntax, grammar, style and/or spelling errors. Thank you!).


Comment on Re: Conditional Search and Replace
Select or Download Code

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others surveying the Monastery: (11)
As of 2014-04-18 18:45 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    April first is:







    Results (471 votes), past polls