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.
|