You might want to explore using a hash with the regular expression as the key and the replacement text as the value. You can use compiled regular expressions as hash keys. You might need to consider using
\Q and
\E or
quotemeta when compiling the regular expressions. In the script below I read the patterns and corresponding replacements from the
DATA file at the end of the script and the patterns contain no spaces so a simple
split on white space is sufficient. Your patterns may be more complex.
use strict;
use warnings;
my %substitutions = ();
while ( <DATA> )
{
chomp;
my ($pattern, $replace) = split;
my $rxPattern = qr{(?si)$pattern};
$substitutions{$rxPattern} = $replace;
}
my $str = q{a capital M and Fish};
print qq{$str\n};
$str =~ s{$_}{$substitutions{$_}}
for keys %substitutions;
print qq{$str\n};
__END__
\s*M\s* MALE
\s*F\s* FEMALE
The output produced is
a capital M and Fish
a capitalMALEandFEMALEish
I hope this is of use.
Cheers,
JohnGG
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.