Better:
$string =~ s/(a|b)/$map{ $1 }/g;

You may be able to construct the pattern out of the hash keys:

$pattern = join '|', map quotemeta, keys %map; $string =~ s/($pattern)/$map{ $1 }/go; # /o only if the pattern never + changes
For not too recent perls, you get a better performance if you build the pattern out of the keys with a module like Regexp::Assemble or Regex::PreSuf;
use Regex::PreSuf; my $pattern= presuf(keys %map); $string =~ s/($pattern)/$map{ $1 }/go;

Allegedly, the most modern perl will optimize it for you, and possibly even with better (faster) results.

update (July 9) ysth sent me a msg with a caution for the case where one of the hash keys is a prefix of another key, for example: ('foo', 'food'). In that case, to make sure the longest key is matched, you should sort the keys when constructing the pattern so the longest key comes first. ysth proposed:

$pattern = join '|', map quotemeta, sort { length($b) <=> length($a) } + keys %map;
which will work, but so will this:
$pattern = join '|', map quotemeta, sort { $b cmp $a } keys %map;
because with two strings where one is a prefix of another, the longer one will compare as "greater" than the shorter one.

You need not worry when using Regex::PreSuf because it'll always attempt to match the longest string, first.


In reply to Re^2: ugly code by bart
in thread ugly code by fubber

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.