I thought about using $1 and $2, but that doesn't seem to work.
I'm not saying that this is the preferred solution... but just for
general interest: in those cases, you could use \1 and \2 instead, e.g.
my $s = q(var1='1' var2="2" var3="'3'" var4='"4"');
while ($s =~ m/(\w+)=(["'])(.*?)\2/g) {
print "(using quote $2): $1 = $3\n";
}
Output:
(using quote '): var1 = 1
(using quote "): var2 = 2
(using quote "): var3 = '3'
(using quote '): var4 = "4"
The ugly thing is that with input such as (incorrect according to your spec)
my $s = q(var1='1" var2="2');
it would extract the entire '1" var2="2' substring as
one single quoted value...
You'd have to work around that by disallowing some separator (like
whitespace) within the quoted string, or some such, to properly group
the assignments (e.g. using the char class [^\s] in place of .).
That's problematic if you do need to allow spaces in the quoted
values, though.
Update: fixed/simplified [^\2]+? —> .*? in
the regex, because on second thought, when looking at hipowls's
suggestion below, it occurred to me that (a) the backref in the character
class doesn't actually work :), (b) even if it did, that part of
the regex would've been redundant anyway, due to the non-greedy match...
|