Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
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!).

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others wandering the Monastery: (5)
As of 2016-12-10 09:58 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    On a regular basis, I'm most likely to spy upon:













    Results (160 votes). Check out past polls.