in reply to "While" effect on regex?
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
The /g flag which stands for 'global matching' changes that behavior.my @matches = 'aXaYaZ' =~ /(a[XYZ])/g; say "@matches"; --output:-- aX
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^2: "While" effect on regex?
by Anonymous Monk on Feb 17, 2013 at 08:10 UTC | |
by CountZero (Bishop) on Feb 17, 2013 at 16:24 UTC | |
by Anonymous Monk on Feb 17, 2013 at 16:30 UTC | |
by CountZero (Bishop) on Feb 17, 2013 at 16:45 UTC |