As long as the web server machine can open the debugger window,
this ptkdb debugger option works fine in a CGI program.
In order to allow a any machine to open a window on your
X-Windows display, execute xhost +.

The DISPLAY environment variable needs to
be set in the BEGIN block of the perl code.

This technique is complementary to the more common
techniques of sending the error messages to the browser,
examining the error logs, and diagnostic print statements.

The nice part about this technique is that you can single
step through the CGI program, set breakpoints, examine
and change variables, and watch the CGI output being
rendered in the browser one step at a time. All these
features are available in the easy-to-use graphical
user interface of ptkdb.

Note:tilly asked me to post this here after
I wrote a much shorter version in the snippets section.
I fixed a few spelling errors, also.

You don't need ptkdb nor X. I've debugged CGIs using the standard Perl debugger while telnet'd into the web server. Sorry, I don't have the details handy. I had to chmod the pseudo tty that telnet gave me so that the world could read/write it, then modify the CGI script to invoke the Perl debugger and tell it to use that tty as the debugging console.

I don't recall exactly what method I used to tell the Perl debugger to use an alternate tty. You can use the PERLDB_OPTS environment variables and/or the .perldb (or perldb.ini) config file but I suspect either of these will require a trick similar to:

I think I can see where you are headed with this,
but I didn't get your example to work yet.
Your idea would be especially useful on systems
with firewall constraints that
do not allow X Window traffic to pass from the
web server to the developer's X server.

This is what I tried:
I used telnet to log onto the web server,
and made a little cgi program that used your code.
I set the TTY variable to be the same as the
device used by my telnet window. I used chmod to open
up read and write priviledges on the TTY device for
the telnet window.
I invoked the CGI from my web browser and I saw the
prompt for the debugger come up in my telnet window.
But when I typed a debugger command, the command went
to the shell instead of going to the debugger.
So the debugger commands weren't executed, and the
CGI program hung.