Back when I wrote perlretut , code expressions (?{code}) and (??{code}) were relatively new beasts in the regex menagerie. I thought they were clever and the variable backtracking was a little bit magical.

The trouble was, I couldn't come up with any examples where code expressions really nailed the problem. So for the tutorial I created a cute, but useless, example of matching Fibonacci strings:
# detects if a binary string 1101010010001... # has a Fibonacci spacing 0,1,1,2,3,5,... of the 1's $x = "1101010010001000001"; $s0 = 0; $s1 = 1; # initial conditions print "It is a Fibonacci sequence\n" if $x =~ /^1 # match an initial '1' ( (??{'0' x $s0}) # match $s0 of '0' 1 # and then a '1' (?{ $largest = $s0; # largest seq so far $s2 = $s1 + $s0; # compute next term $s0 = $s1; # in Fibonacci sequence $s1 = $s2; }) )+ # repeat as needed $ # that is all there is /x; print "Largest sequence matched was $largest\n";
This prints
It is a Fibonacci sequence Largest sequence matched was 5

Since then, I have written many regexes, but haven't come across any code that needed code expressions, as opposed to a combination of simpler regexes and perl code.

My question is: Has anyone found a good use for code expressions in their regex work?

-Mark

In reply to Useful Uses of regex code expressions? by kvale

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.