Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

Re^3: Modifying pos() from within (?{...})

by haukex (Archbishop)
on Apr 26, 2018 at 13:50 UTC ( [id://1213606]=note: print w/replies, xml ) Need Help??


in reply to Re^2: Modifying pos() from within (?{...})
in thread Modifying pos() from within (?{...})

I assume then, should the data I'm parsing with the regex be well formatted, then pos() will never be reset and so the /c modifier is not needed?

Note that the condition on the while loop is the regex, so the loop will run while the match is true, so the last match executed will always be a failed one. The question then is why it failed, because it reached the end of string (= successful overall parse) or it did not, which is why I compare pos to length - but for pos to be available there, I need /c.

use warnings; use strict; my $string = " foo bar quz "; print "String: '$string' length: ",length($string),"\n"; print "### Successful match with /c:\n"; pos($string)=undef; print "<$1>\n" while $string =~ / \G \s* (foo|bar|quz) \s* /xgc; print "pos: ",pos($string)//'undef',"\n"; print "### Failed match with /c:\n"; pos($string)=undef; print "<$1>\n" while $string =~ / \G \s* (foo|bar) \s* /xgc; print "pos: ",pos($string)//'undef',"\n"; print "### Successful match without /c:\n"; pos($string)=undef; print "<$1>\n" while $string =~ / \G \s* (foo|bar|quz) \s* /xg; print "pos: ",pos($string)//'undef',"\n"; print "### Failed match without /c:\n"; pos($string)=undef; print "<$1>\n" while $string =~ / \G \s* (foo|bar) \s* /xg; print "pos: ",pos($string)//'undef',"\n"; __END__ String: ' foo bar quz ' length: 13 ### Successful match with /c: <foo> <bar> <quz> pos: 13 ### Failed match with /c: <foo> <bar> pos: 9 ### Successful match without /c: <foo> <bar> <quz> pos: undef ### Failed match without /c: <foo> <bar> pos: undef

Another use for /c is described in "\G assertion" in perlop (under "Regexp Quote-Like Operators"): basically, attempting to apply multiple different regexes at the same point in a string until you find one that matches.

Log In?
Username:
Password:

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

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

    No recent polls found