Could you perhaps explain why?

In conjunction with the SO explanations linked by rminner, consider this variation on rminner's code. The  @- special match array variable (see perlvar) is used to show the starting position of the match that is found:  $-[0]
Then pos is printed to show the string position from which further matching will continue. The second match never finds  'foo' because when it trys to do so, it's already past it! Now remove all the  /g regex modifiers from all the matches and see what happens. See perlre, perlretut.

>perl -wMstrict -le "my $string = 'foo bart bare'; ;; if ($string =~ m{bar}g) { print qq{found bar at offset $-[0]}; } print 'string pos is ', defined(pos $string) ? pos $string : 'UNDEF'; ;; if ($string =~ m{foo}g) { print qq{found foo at offset $-[0]}; } print 'string pos is ', defined(pos $string) ? pos $string : 'UNDEF'; ;; if ($string =~ m{bar}g) { print qq{found bar at offset $-[0]}; } print 'string pos is ', defined(pos $string) ? pos $string : 'UNDEF'; " found bar at offset 4 string pos is 7 string pos is UNDEF found bar at offset 4 string pos is 7

In the code as shown, the second  'bar' match at offset 9 is never found because the intervening  m{foo}g match fails and 'resets' the string match position. With all  /g modifiers in place, try matching with  m{foo}gc (note the added  /c modifier) and see what happens.


In reply to Re^3: regex problem: doesn't work on the first search but works on the second by AnomalousMonk
in thread regex problem: doesn't work on the first search but works on the second by onlyauto

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.