Your Method #3 doesn't work because a m//g regex with capture groups in list context returns a list of the substrings matched by any capturing parentheses in the regular expression, that is, ($1, $2...), repeated for each match (see my node here).

my @output = $x=~/(^A|^B)(.+)$/mg; print Dumper(\@output); # $VAR1 = ['A', ' data for A', 'B', ' data for b', 'A', ' data for A', + ...

I would guess that in Method #2, the overhead of splitting the string into lines and then running a regex match on each of the lines (as opposed to a single regex iterating through a single string) might be what is causing the slowdown.

But I would address your comment in Method #1 about using names as follows, and this is the variation I might suggest in this case: named capture groups (see also perlre).

while ( $x =~ m{^ (?<name>A|B) (?<data>.+) $}xmg ) { print "$+{name} method1 $+{data}\n" }

(There are of course plenty of other ways, such as m/\G.../gc parsing.)


In reply to Re: Extracting /regex/mg in a while loop by haukex
in thread Extracting /regex/mg in a while loop by NetWallah

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.