in reply to Double Capturing Parentheses
Take the regexp /(\w)(\w)/, and the string "same old show".
Result:$_ = "same old show"; # scalar, one at a time: while(/(\w)(\w)/g) { print "while: $1 (+ $2)\n"; } # list context, one go @list = /(\w)(\w)/g; print "List: @list\n"; # list context, foreach loop foreach(/(\w)(\w)/g) { print "foreach: $_\n"; }
while: s (+ a) while: m (+ e) while: o (+ l) while: s (+ h) while: o (+ w) List: s a m e o l s h o w foreach: s foreach: a foreach: m foreach: e foreach: o foreach: l foreach: s foreach: h foreach: o foreach: wAs you can see, the foreach produces twice as much output as the while. That is because each match returns a list of two items, $1 and $2, and the regexp in list context returns a (flattened) list of such lists, as you can see in the example in the middle. foreach uses this grand, flattened list to loop through, thus for each each match you see a loop for $1, and next one for $2.
OTOH the while takes one pair of matched items each time, thus it'll loop half as many times.
In your particular example, the regexp is /((.))/. You still have a $1 and a $2, even though they capture the same thing — but you ignore $2. That's why you don't see it appear. Modifying my code to match your regexp and string, I get:
Result:$_ = "abc"; # scalar, one at a time: while(/((.))/g) { print "while: $1 (+ $2)\n"; } # list context, one go @list = /((.))/g; print "List: @list\n"; # list context, foreach loop foreach(/((.))/g) { print "foreach: $_\n"; }
while: a (+ a) while: b (+ b) while: c (+ c) List: a a b b c c foreach: a foreach: a foreach: b foreach: b foreach: c foreach: cwhich matches your result.
In summary: you simply ignored to output the contents of $2 in your first snippet, the while loop.
|
|---|