There was a formatting error in u671296's code. The line $positions{$key} = $pos; should read $positions{$key} = [$pos];, in order to create an array reference. Then the push in the else branch will have an array reference to push into, rather than just a scalar number.