Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??

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":



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others chilling in the Monastery: (6)
As of 2024-04-24 06:53 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found