CombatSquirrel's reply is one way to do it; note that it involves two separate regex compilations. Therefor, the way I'd prefer to do this would be

print $1 if /^(\d)/g and /\G(\d{$1})/g

Note the /g modifier on the first regex. Since it's called in scalar context, this makes the regex engine remember the end of the last match for that string; you can match that position in the next pattern using \G. This way, the second regex starts matching where the last one left off.

If you're not looking for a match however, so much as for a way to handle data structures, then maybe unpack is your ticket.

print unpack "A/A*", $_

The A/ bit of the template tells unpack that you want to take one A, ie one ASCII character, as the length count to use for the next template. The A* will then grab that many ASCII characters from the rest of string. If you need to make sure they're digits, that will have to be an extra step. If the count is not a digit, the A* will grab zero characters. So maybe what you're doing is best done as

my $num = unpack "A/A*", $_; print $num if length($num) and $num !~ /\D/;

This is a little more awkward, but if the data structure you're dealing with is larger, it scales much better: you can put all of the data structure extraction into a single unpack template, and then validate the various bits you pulled out with individual patterns.

The multi-regex solution on the other hand becomes messier as the structure becomes larger, because extraction and validation are intermixed.

Makeshifts last the longest.


In reply to Re: RegExp madness by Aristotle
in thread RegExp madness by palandir

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.