When I run a Perl script, how can I debug it? For example, in ksh I add the -x
flag. But how I do the same in Perl?
If using an interactive debugger is OK for you, you can try perldebug.
If you want to do remote debugging (for CGI or if you don't want to mess output with debug command line), use this:
Given test:
use v5.14;
say 1;
say 2;
say 3;
Start a listener on whatever host and port on terminal 1 (here localhost:12345
):
$ nc -v -l localhost -p 12345
For readline support use rlwrap (you can use on perl -d
too):
$ rlwrap nc -v -l localhost -p 12345
And start the test on another terminal (say terminal 2):
$ PERLDB_OPTS="RemotePort=localhost:12345" perl -d test
Input/Output on terminal 1:
Connection from 127.0.0.1:42994
Loading DB routines from perl5db.pl version 1.49
Editor support available.
Enter h or 'h h' for help, or 'man perldebug' for more help.
main::(test:2): say 1;
DB<1> n
main::(test:3): say 2;
DB<1> select $DB::OUT
DB<2> n
2
main::(test:4): say 3;
DB<2> n
3
Debugged program terminated. Use q to quit or R to restart,
use o inhibit_exit to avoid stopping after program termination,
h q, h R or h o to get additional info.
DB<2>
Output on terminal 2:
1
Note the sentence if you want output on debug terminal
select $DB::OUT
If you are Vim user, install this plugin: dbg.vim which provides basic support for Perl.
Use Eclipse with EPIC: It gives you a nice IDE with debugging possibilities, including the ability to place breakpoints and the Perl Expression View
for inspecting the value of variables.
perl -d your_script.pl args
is how you debug Perl. It launches you into an interactive gdb
-style command line debugger.
To run your script under the Perl debugger you should use the -d
switch:
perl -d script.pl
But Perl is flexible. It supplies some hooks, and you may force the debugger to work as you want
So to use different debuggers you may do:
perl -d:DebugHooks::Terminal script.pl
# OR
perl -d:Trepan script.pl
Look these modules here and here.
There are several most interesting Perl modules that hook into Perl debugger internals: Devel::NYTProf and Devel::Cover
And many others.
Note that the Perldebugger can also be invoked from the scripts shebang line, which is how I mostly use the -x
flag you refer to, to debug shell scripts.
#! /usr/bin/perl -d