Site Feed

Monday, December 1, 2008

Using the Perl Debugger Interactively


Sometimes you might want to test a few ideas to implement into a perl script, but you want to see if it will work before you implement it. The Perl debugger is perfect for that.

What is the Perl Debugger?

Here is an intro from man perldebug :

If you invoke Perl with the -d switch, your script runs under the Perl source debugger. This works like an interactive Perl environment, prompting for debugger commands that let you examine source code, set breakpoints, get stack backtraces, change the values of variables, etc. This is so convenient that you often fire up the debugger all by itself just to test out Perl constructs interactively to see what they do.

For example: $ perl -d -e 42

Using the Perl Debugger Interactively

To invoke the perl debugger, simply use the -d option, and give it any name, such as "1", in this example. Instead of specifying "-e 1", you could specify a filename to have perl debug the file.

In this case, we want to use the debugger interactively, so we type:


perl -d -e 1


Loading DB routines from perl5db.pl version 1.28
Editor support available.

Enter h or `h h' for help, or `perldoc perldebug' for more help.

main::(-e:1): 1

DB<1> print hello


DB<2> print "hello";
hello

DB<3>

Notice that the correct syntax for print is to use quotes, and terminate with a semicolon ";". The debugger is a quick way to verify simple constructs.


DB<4> test=123
Can't modify constant item in scalar assignment at (eval 14)[C:/Perl/lib/perl5db.pl:628] line 2, at EOF


DB<5> $test=123


DB<6> print $test;
123

DB<7>

Notice that a scalar requires the dollar sign "$" character for both assignment and calling the variable. This is different for shell scripts, where assignment requires no dollar sign, and invocation requires it. Here in the perl debugger, it is easy to test simple operations.

Notice also that this works on any OS where perl is installed. I run this on Windows and linux.


Here it is on RHEL 5:

-bash-3.2$ perl -d -e 1

Loading DB routines from perl5db.pl version 1.28
Editor support available.

Enter h or `h h' for help, or `man perldebug' for more help.

main::(-e:1): 1

DB<1> print "hello";
print "hello";
hello

DB<2>

So, have fun with the debugger. Of course, as is common in perl, there is more than one way to do things. You can combine options

perl -de 1

And, of course there is always the perl one-liner:

-bash-3.2$ perl -e 'print "hello\n";'
hello
-bash-3.2$

No comments: