http://qs321.pair.com?node_id=837914


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!).