I have experienced strange behavior of using Regex captures for assignment of list elements - which puzzles me a lot, and I could not find an explanation anywhere in the documentation and other places. The code that I use is like this:
$_ = "one 1 two 2 three 3";
my $n = 1;
my @tt = (
/one (\S+)/ ? (one => $1) : (),
/two (\S+)/ ? (two => $1) : (),
/three (\S+)/ ? (three => $1) : (),
);
print "Array: " . join(" ", @tt) . "\n";
Which prints, surprisingly:
Array: one 3 two 3 three 3
while I expect that it will print:
Array: one 1 two 2 three 3
So, when I use //
and ?:
within a list assignment, I always get captures from the last(!) matching expression - be it $1
or $&
or anything else that refers to captures.
When I surround each ?:
with do {}
, everything works as expected, though.
My question is - what I am doing wrong? Is it a bug or some well known (or hidden) feature/behavior that I am not aware of?
Thank you!
PS: If this matters - I use standard perl 5.22.1 on Ubuntu 16.04.2, though the behavior is the same on Perl 5.8.8 and 5.24.1
EDIT: Though the reason for this behavior is the same as in this question - compilation order and post prefix opertors - but the context is quite different and it is not immediately obvious that questions are similar, as the previous question is about passing arguments to a sub, while in my question no subs are involved.