In your script, the second loop is not nested in the first loop. It will be easier to catch bugs like this if at the beginning of scripts you always code
Then check the script before running it, with
perl -c ...
In the case of your script, Perl complains about "Global symbol "@lines" requires explicit package name ..., among others.
This means that you have not declared the variable @lines in the scope of the second loop. Looking to see where @lines is first used, the bug in your code becomes obvious without having to read all the code in detail.
When you errors, it's quickest to fix just one problem at a time and check the script again, repeating until all the errors are gone, before trying to run your code to see what happens. Each time you check the script, look through the list of errors for the earliest line number to fix, since a problem with a quote usually causes error messages in later lines that may not really be errors.
It's also a good habit to declare each variable (use strict forces this), if possible when you first assign it. When you check the script, a typing mistake in the varible name causes an error to appear for the line with the typo in it, unless the typo is in the declaration (then every other use of the variable has an error). And if you declare a variable twice in the same scope, it complains about that too, and this means you have a problem with brackets (maybe improper loop nesting) or a typo in the first or second variable declaration.
Don't worry about remembering this list of causes of errors; I wrote it to help kickstart your productivity. You'll figure them out by yourself soon enough as you gain experience.