Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"
 
PerlMonks  

Re: non-greedy piecewise matching

by ikegami (Patriarch)
on Aug 02, 2007 at 17:40 UTC ( [id://630349]=note: print w/replies, xml ) Need Help??


in reply to non-greedy piecewise matching

The greediness is just your first problem.

Problem #2: You're using the g modifier in list context, causing all the matches to be returned at once. You'll never print anything other than the first file name.

pos $data = 0; my $len = length $data; while (pos $data < $len) { if ( $data =~ m{ \G ( .+? \. xml ) }gcxms ) { print "$1\n"; } }

Problem #3: If there's anything after the last .xml, you have yourself an infinite loop. Checking if pos is less then length is a bad idea when using the c modifier. Fix:

pos $data = 0; for (;;) { $data =~ m{ \G ( .+? \. xml ) }gcxms or last; print "$1\n"; }

Finally: Using the c modifier is rather useless, ugly if you only have one regexp, and it's rather complex (as shown by the number of errors). Fix:

while ( $data =~ m{ \G ( .+? \. xml ) }gxms ) { print "$1\n"; }

Tip: If you really did have a use for c (e.g. if you were writting a lexer), then you'd have multiple regexps, and aliasing $_ to the variable containing the text would be worthwhile.

for ($data) { pos() = 0 for (;;) { /\G ... /xgc && do { ...; next }; /\G ... /xgc && do { ...; next }; /\G ... /xgc && do { ...; next }; last; }

Replies are listed 'Best First'.
Re^2: non-greedy piecewise matching
by mifflin (Curate) on Aug 02, 2007 at 19:12 UTC
    gads!
    Now I know why the damian put the following quote at the begining of his chapter...

    Some people, when confronted with a problem, think:
    "I know, I'll use regular expressions".
    Now they have two problems.
    -- Jamie Zawinski

    Thanks.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others scrutinizing the Monastery: (9)
As of 2024-03-28 09:10 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found