Here is one way to do it. In the case of only three $foo =~ matches this method seems foolish, but if your list of matches and substitutions is long enough, it's worthwhile. It is also possible to put the pattern as a hash key and the substitution as a hash value, or vice versa. Then iterate through "each %hash".

foreach (qq/frog toad/, qq/man boy/, qq/woman girl/) { my ( $pattern, $substitution) = split /\s/, $_; $foo =~ s/\Q$pattern\E/$substitution/g; }

Another way would be like this:

my %testhash = ( qw/frog toad man boy woman girl/ ); foreach (keys %testhash) { $foo =~ /\Q$_\E/$testhash{$_}/; }

Note that I added "\Q" and "\E" to both regexps. This is to ensure that the variable being interpolated into the regexp doesn't have any possible metacharacters interpreted in the regexp. So if you happen to be testing 'C:\data' (a lousy example, but stay with me), the regexp engine won't see it as 'C:[0-9]ata'.

In your example, the \Q and \E quotemeta function isn't needed. And there are plenty of cases where its function is undesirable (for example, what if you WANT 'C:\data' to be interpreted as 'C:[0-9]ata'), but I included them in my example to ensure that you are matching in the most simple way.

I don't see any way of just having one iteration of $foo =~ s/// do it all though.

Dave

"If I had my life to do over again, I'd be a plumber." -- Albert Einstein


In reply to Re: multiple (different) substitutions on same $foo by davido
in thread multiple (different) substitutions on same $foo by jonnyfolk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • 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:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.