hi,

time ago a monk asked how to s/// using an hash for key/value substitution.

knowing the keys of the hash, it would be easy to:

s/(key1|key2|key3)/$hash{$1)/g;
in a more generic way, the RE can be built using qr:
my $re = join '|', keys %dict; $re = qr|($re)|; s/$re/$hash{$1}/g;
with a CPAN module, you can:
use Regexp::Assemble; my $ra = Regexp::Assemble->new; $ra->add($_) for keys %dict;
which returns a more clever pattern. Or:
s/(\w+)/$dict{$1}||$1/ge;
(Note some differences between those approaches. The last one will "update" the string also when it shouldn't, by replacing with the same text. this can be a problem if i want to match 'bcd' in 'abcde' -- in this case s/// will change abcde with abcde and pass over, it does not check bcd!)

I looked on perlre to findout if we can do assertions on a RE, (?{code}) is an "always true" statement1, a pity we can't use to stop the parsing. but after some digging i found that (?(?{cond})|(?!)) fails if cond isn't true, so:

s/(\w+)(?(?{$dict{$1}})|(?!))/$dict{$1}/g;
This way avoid to prepare the RE before, but match bcd against abcde.

This seems to be a misleading (yet usefull) feature. it means that (${code}) isn't an "always true" assertion. But is it reliable enough to be used?

1 -- seems this will be changed in perl 6.

Update: corrected a missing ) in the last RE.


In reply to regex s/// using hash by oha

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.