Hi Boyd.Ako,

I don't know the specifics as to how /g works.

/g on an m// match is documented in perlop, in this case: "In scalar context, each execution of m//g finds the next match, returning true if it matches, and false if there is no further match." Since the regexp is being used in a while loop, without the /g modifier it would simply match the first occurrence every time and the loop would never end. With /g, the match advances through the string.

Alternatively: "The /g modifier specifies global pattern matching--that is, matching as many times as possible within the string. ... In list context, it returns a list of the substrings matched by any capturing parentheses in the regular expression." Without /g, it would only find the first match.

When you add the /g and the capturing group to codiac's code it works:

use warnings; use strict; my $text = <<'END'; <y><ReportHost>one</ReportHost> <x>test</x></y> <ReportHost> two </ReportHost> <ReportHost><z>thr</z>ee</ReportHost> END # m//g in scalar context while ($text=~ m{<ReportHost[^>]*>((?:(?!</ReportHost>).)*)</ReportHos +t>}sg) { print "a: \"$1\"\n"; } # m//g in list context my @m = $text=~ m{<ReportHost[^>]*>((?:(?!</ReportHost>).)*)</ReportHo +st>}sg; print "b: \"$_\"\n" for @m; __END__ a: "one" a: " two " a: "<z>thr</z>ee" b: "one" b: " two " b: "<z>thr</z>ee"

Hope this helps,
-- Hauke D


In reply to Re^4: No tools? Use Perl?! by haukex
in thread No tools? Use Perl?! by Boyd.Ako

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.