My guess is because one of your while loops never hits an end condition. You're probably walking off the end of @ary. If you had warnings enabled, Perl would tell you about this.
Revise the code to use the warnings pragma or the -w flag, and you'll have an easier time tracking this down.