in reply to Nested if and while statements

Your regex tests are happening against $_ which is context-sensitive, ie. it will be changed by the loops. If that isn't what you want, then test against a persistent lexical variable instead. See perlvar for all the details on $_ and friends.