In Perl, how can I use one regex grouping to capture more than one occurrence that matches it, into several array elements?
For example, for a string:
I'm not saying this is what you should do, but what you're trying to do is write a Grammar. Now your example is very simple for a Grammar, but Damian Conway's module Regexp::Grammars is really great at this. If you have to grow this at all, you'll find it will make your life much easier. I use it quite a bit here - it is kind of perl6-ish.
use Regexp::Grammars;
use Data::Dumper;
use strict;
use warnings;
my $parser = qr{
<[pair]>+
=(?:""|)
var\d+
<[MATCH=literal]> ** (,)
\S+
}xms;
q[var1=100 var2=90 var5=hello var3="a, b, c" var7=test var3=hello] =~ $parser;
die Dumper {%/};
Output:
$VAR1 = {
'' => 'var1=100 var2=90 var5=hello var3="a, b, c" var7=test var3=hello',
'pair' => [
{
'' => 'var1=100',
'value' => '100',
'key' => 'var1'
},
{
'' => 'var2=90',
'value' => '90',
'key' => 'var2'
},
{
'' => 'var5=hello',
'value' => 'hello',
'key' => 'var5'
},
{
'' => 'var3="a, b, c"',
'key' => 'var3',
'list' => [
'a',
'b',
'c'
]
},
{
'' => 'var7=test',
'value' => 'test',
'key' => 'var7'
},
{
'' => 'var3=hello',
'value' => 'hello',
'key' => 'var3'
}
]