in reply to out of memory!
Are you running under use strict; use warnings;? Also, your line until($dist[$b]<0); makes me nervous. What if this condition is never true? Or $b exceeds the size of the array $dist?