The best (for some definition of that term) solution I have found for the problem of having variable numbers of caturing parens that may or may not be part of specific matches, is to use $^N, some our variables and embedded (?{code}) blocks.

our( $foo, $bar, $qux); $string =~ m[ ( some regex ) (?{ $foo = $^N }) other stuff ( a conditional capture ) (?{ $bar = $^N }) | ( another possibility ) (?{ $bar = $^N }) ... ( a final piece ) (?{ $qux = $^N }) ]x;

Using this method, you know that when the regex engine is finished, exactly where it has put whatever it has captured and you no longer have to play musical chairs trying to work it out.

With care, it is extensible to extremely complex regexes with essentially any number of captures. You can also arrange that multiple captures resulting from repeating regexes be pushed onto an array. This is something that I know of no other usable way of doing.

There is a performance penalty with this technique, and I'm not keen on the use of globals, but until we get capture-to-named-vars (which seems to be a part of P6 grammers), it is the least bad of a set of bad alternatives.


Examine what is said, not who speaks.
"Efficiency is intelligent laziness." -David Dunham
"Think for yourself!" - Abigail
Hooray!


In reply to Re: Many birds, single cage... by BrowserUk
in thread Many birds, single cage... by monsieur_champs

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.