http://qs321.pair.com?node_id=1173856


in reply to Problem with capturing all matches with regex

I was hoping that the named-capture variables would collect all of your matches, but they also only keep the last one, so as an alternative, I can only suggest embedded code (the (?:...)++ ensures no backtracking over your push @lhs code):

#!/usr/bin/perl use 5.010; use Data::Dumper; my $equation = '979x + 87y - 8723z = 274320'; my @lhs; die "match failed" unless $equation =~ / ^ (?: (?<coeff>.*?) (?<var>[xyz]) (?{ push @lhs, $+{coeff}, $+{var} }) )++ \s* = \s* (?<rhs>.*) $ /ix; my $rhs = $+{rhs}; say Dumper([\@lhs, $rhs]);

This approach also allows you to construct something more interesting than a flat list, should that be desirable.

Good Day,
    Dean

Replies are listed 'Best First'.
Re^2: Problem with capturing all matches with regex
by igoryonya (Pilgrim) on Oct 12, 2016 at 15:23 UTC
    Oh, yea, you have the best solution!
    I wanted to use embedded code, but, since've never done it, couldn't figure out how to use it. Read about on perlre, but didn't understand how to us it, exactly.
    You have a very good, understandable example.
    Now I can optimize a lot of my regexes with it. :)
      I wanted to use embedded code ... Now I can optimize a lot of my regexes with it.

      Beware. Such "optimization" is often a snare and a delusion. Many times it is more conducive to efficiency to understand how the Perl regex engine captures and returns groups and to take advantage of these inherent mechanisms. Also be aware that previous to Perl version 5.18 (I think), there existed a bug that caused weird interactions between embedded regex code and "external" (if that's the right term) my variables.

      OTOH of course, sometimes embedded code is just the only way to do it. :)


      Give a man a fish:  <%-{-{-{-<

        Adding code ("actions") into your patterns is how real-world parser generators generally work. Perl6 has gone that direction, but the Perl5 syntax for doing it is obscenely bletcherous.
        Yes, I've looked into the perlretut (or something, forgot) section. It said, that it's a new buggy feature.
        But, I kind of dreamed of feature like that, because, I have one megapattern, in one of my programs, that I've had to create an entire subroutine for it to parse with many different regexes and ifs thenths, that spans for about 3 screen pages. I was hoping for a feature like this to make that pattern matching subroutine to make more consize.
        I think, in that sub's case, I am targetting not the speed, but readability and managedness of the code :)