http://qs1969.pair.com?node_id=645411

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.