I am looking to simplify a pattern. If I have a string my $x = "0.01 NaN 2.30 4.44"; then the following pattern finds the items present:

my $r1 = qr/([Na0-9\.\-\+]+)\s+ ([Na0-9\.\-\+]+)\s+ ([Na0-9\.\-\+]+)\s+ ([Na0-9\.\-\+]+)/x;

Notice that the same capture group criteria are repeated. I wonder how I may write that so it is simpler, shorter, and all on one line. Here is some pseudo-code to try to show what I am aiming for: my $r1 = qr/(?=([Na0-9\.\-\+]+)\s+){4}/

However, I've tried that and some permutations without luck:

#!/usr/bin/perl use strict; use warnings; my $x = "0.01 NaN 2.30 4.44"; # the following works as desired my $r1 = qr/([Na0-9\.\-\+]+)\s+ ([Na0-9\.\-\+]+)\s+ ([Na0-9\.\-\+]+)\s+ ([Na0-9\.\-\+]+)/x; my ($d, $e, $f, $g) = ($x =~ m/$r1/x ); print qq($d, $e, $f, $g\n); # the following finds the first number twice my $r2 = qr/(?=(([Na0-9\.\-\+]+)\s*)){4}/x; ($d, $e, $f, $g) = ($x =~ m/$r2/x ); print qq($d, $e, $f, $g\n); # the following finds a null prior to the first item my $r3 = qr/((?=([Na0-9\.\-\+]+)\s*){4})/x; ($d, $e, $f, $g) = ($x =~ m/$r3/x ); print qq($d, $e, $f, $g\n); exit(0);

How can I write that pattern so that the pattern it contains is repeated but not locked into the values found in the very first match? Is this a case for using recursive patterns?


In reply to Repeating a capture group pattern within a pattern by mldvx4

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.