I'm trying to make substitutions within a block of text using the following:
#!/usr/bin/perl -w use strict; my %subs = ( qr/(\d+)F/i => sub { warn "Matched F with $1\n"; return sprintf("%.u" , ($1 - 32) / 1.8) . 'C' }, qr/(\d+)C/i => sub { warn "Matched C with $1\n"; return sprintf("%.u" , ($1 * 1.8) + 32) . 'F' }, ); my $html = do { local $/; <DATA> }; warn $html; foreach my $key (keys %subs) { warn "checking key: $key\n"; $html =~ s/$key/$subs{$key}->()/eg; warn $html; } warn $html; __DATA__ convert 180F to C convert 180C to F convert 30" to cm etc
If you look at the output of the code; you'll see that once converted, the next regex converts it back..
convert 180F to C convert 180C to F convert 30" to cm etc checking key: (?i-xsm:(\d+)C) Matched C with 180 convert 180F to C convert 356F to F convert 30" to cm etc checking key: (?i-xsm:(\d+)F) Matched F with 180 Matched F with 356 convert 82C to C convert 180C to F convert 30" to cm etc convert 82C to C convert 180C to F convert 30" to cm etc
I assume the solution is to use the global match modifier \G within a while loop but can't get my head around it - if possible I'd like to maintain a hash of qr's to make the code easier to maintain as I extend it. Hope someone can help point me in the right direction! Thanks

In reply to Global replace issue by Anonymous Monk

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.