Am I right to say I should not set variables like this before the FastCGI loop, but to get their values for each response within the loop?
yes , absolutely.
Deciding whether a user is logged in (authentication), or allowed to view something (authorization), needs to happen from within the loop before you decide what kind of content (page) to return
How do I prevent bugs like this from happening?
proper scoping , read CGI to mod_perl Porting. mod_perl Coding guidelines, Lexical scoping like a fox, Variable Scoping in Perl: the basics