1. This code will produce the first matched duplicate word infinitely. It seems that the second "while" evaluate the condition of regex matching unlimited times. Why doese this happen? Does the matching only happen once?

In scalar context, the match operator returns 0 (no match) or 1 (match). The conditional for a while loop is a boolean context, and a boolean context is considered a scalar context because a boolean context demands either a number or a string, which are both scalars. Anything else is converted to a number or string, and then the number or string is evaluated as being true or false.

Any function (or operator) in your code is replaced by the function's return value. So in your while loop conditional, the match operator will return 1 if it finds a match, and therefore your while loop becomes:

while (1) { ... }

Also, because you have a capture group in your regex, the match operator sets $1. The end result is this loop:

while (1) { say $1; }

The m// operator only looks for the first match and then quits:

use strict; use warnings; use 5.012; if ('aXaYaZ' =~ /(a[XYZ])/ ) { say $1; } --output:-- aX
my @matches = 'aXaYaZ' =~ /(a[XYZ])/g; say "@matches"; --output:-- aX
The /g flag which stands for 'global matching' changes that behavior.


In reply to Re: "While" effect on regex? by 7stud
in thread "While" effect on regex? by lightoverhead

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.