I don't know what happens inside your subroutine or in your script since you don't provide a lot of information.
Anyway, i do think, you probably messed around with the scope of your variables together with the use of references
"We all agree on the necessity of compromise. We just can't agree on when it's necessary to compromise." - Larry Wall.