It is very common to have a switch statement or dispatch style cgi script based on some query param ('mode' in your case). To make life easier, this is exactly what
CGI::Application does. While this doesn't directly fix your current code, it would make it a lot easier to understand and maintain since it provides a cleaner execution path.