I think you're confused on a number of points. First off, you can't have a variable number of regex matches if you don't use /g. So if you want to go beyond hard-coding your regexes, you need to get over it.

Second, if you want to name your variables $d1, $d2, etc, you're just contradicting yourself again. You're asking how to know how many variables to create before you know how many matches you'll have. I suppose you could write a bunch of code to eval a string, but using an array is so simple.

Third, /g can be used in loop constructs, which allow you to examine your data as you're parsing it. Very simple parsers are very easy to write. For example:

$s = 'abc 1 23 do 456 re 789 me 0123 456 2 23 456 789 0123 456'; push @results, ("This has " . length($1) . " digits: $1") while $s =~ /(\d+)/g; print "$_\n" for @results; # Prints: # This has 1 digits: 1 # This has 2 digits: 23 # This has 3 digits: 456 # This has 3 digits: 789, etc.
Or you can look for more complicated patterns:
$s = '1 23 456 789 0123 456 2 23 456 789 0123 456'; push @results, ("This looks like a word: $1") while $s =~ /((?:\b\d{1, +2}\s+)+\b\d{3,})/g; print "$_\n" for @results; # Prints: # This looks like a word: 1 23 456 # This looks like a word: 2 23 456

It's not really clear from what you've written what you're trying to do. But capturing a varying number of results is not hard if you get over the idea of using named scalars.

--marmot


In reply to Re^5: Variable matching on a regex by furry_marmot
in thread Variable matching on a regex by LaintalAy

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.