Without looking at your actual problem, and recognizing that you're doing this as an exercise, can I nonetheless recommend
to reformat your code, leaving you free for other more useful things? Parsing Perl is notoriously difficult, most say impossible.