in reply to foreach (shenanigans)

Replace the foreach with a while and your problem is solved.

The point is that in the foreach the regular expression gets evaluated in list context, and that the match which sets the $1 and $2 is the last one. After that the loop is done a number of times, but each time with exactly the same $1 and $2.

With a while on the other hand, the regex is evaluated each time through the loop and sets the $1 and $2 to the appropriate values.

Hope this helps, -gjb-