Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

Re: "While" effect on regex?

by 7stud (Deacon)
on Feb 17, 2013 at 01:51 UTC ( [id://1019093]=note: print w/replies, xml ) Need Help??


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
my @matches = 'aXaYaZ' =~ /(a[XYZ])/g; say "@matches"; --output:-- aX
The /g flag which stands for 'global matching' changes that behavior.

Replies are listed 'Best First'.
Re^2: "While" effect on regex?
by Anonymous Monk on Feb 17, 2013 at 08:10 UTC
    why is the second while loop needed ?
    while(<>) { while( m/\b (\w\S+) ....
    and not just ?
    while(<>) { if ( m/\b (\w\S+) ...
      The first while loop reads in the data to be matched. The second while loop goes through all the matches (if the g modifier is added).

      CountZero

      A program should be light and agile, its subroutines connected like a string of pearls. The spirit and intent of the program should be retained throughout. There should be neither too little or too much, neither needless loops nor useless variables, neither lack of structure nor overwhelming rigidity." - The Tao of Programming, 4.1 - Geoffrey James

      My blog: Imperial Deltronics
        you mean that the while loop executes for each match of /g?
        so if /g matches 2 times then the while block will be executed twice?

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1019093]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others meditating upon the Monastery: (5)
As of 2024-04-24 08:10 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found