Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

(${code}) Regex - Iteration

by zer (Deacon)
on Oct 17, 2007 at 09:34 UTC ( #645411=perlquestion: print w/replies, xml ) Need Help??

zer has asked for the wisdom of the Perl Monks concerning the following question:

Top of the mornin!

Ive been hacking around all night and I have gargled some code which is confusing me.

perl -wle '$_="a"x20;s/(?{print "${^O}rules".-"${0}macs"})//g'|wc -l
I was obfuscating sorry.

the idea is that no matter what you change the length of $_ to, it is always going to run the print command 2x the number plus two. I am speculating that this number may change on different platforms. But anyways. What is the logic here? What is the regex doing to come to that magical number of executes?

Replies are listed 'Best First'.
Re: (${code}) Regex - Iteration
by oha (Friar) on Oct 17, 2007 at 09:45 UTC
    it match 2 times for every boundary1 for a total of 42. first time is obvious, the second time match but fail at end, cauz it match the same length (thanks god, unless it will match forever).

    use re 'debug'; helps.

    Oha

    1 -- having 20 chars length strings mean 19 places between the chars and 2 more, one at start and one at the end

Re: (${code}) Regex - Iteration
by ikegami (Patriarch) on Oct 17, 2007 at 13:16 UTC

    It starts matching at pos 0 and succeeds
    It starts matching at pos 0 and fails
    It starts matching at pos 1 and succeeds
    It starts matching at pos 1 and fails
    It starts matching at pos 2 and succeeds
    It starts matching at pos 2 and fails
    ..
    It starts matching at pos 20 and succeeds
    It starts matching at pos 20 and fails

    It fails because the match would be identical (same start pos and length) as the previous match. Since it only fails *after* processing the (?{code}), it prints (X+1)*2 times.

    What did you want it to do? The following matches X times.

    s/.(?{ print ++$x,"\n" })//g

    Update: Fixed regex. It had an extra . in it.

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others rifling through the Monastery: (4)
As of 2022-08-08 08:12 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?