adamcrussell

Perl REPL/Debug

While there are several modules available on CPAN which provide a Read Eval Print Loop the classic technique for executing Perl statements interactively is via the perl debugger. To start a REPL session execute the following:

perl -d -e 0

And you will enter the debugger and be able to execute commands interactively, along with the ability to use debugging functions. For example,

$ perl -d -e 0

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

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

main::(-e:1): 0
DB<1> $a = 2;

DB<2> $b = $a * 9;

DB<3> print "B!" if($b > $a);
B!
DB<4> x $b
0 18
DB<5> 

The debugger commands are pretty well documented if you're interested in using them.

In order to get the debugger into this interactive mode you specify the -d and -e command line options. After the -e you could specify whatever code you'd like but in most cases, if you are doing this for REPL purposes, you can specify the shortest possible syntactically correct Perl code which is simply a single numeric value. The use of 0 is arbitrary. What happens is that whatever code follows -e is used in the interactive debugging session. Since we don't really care about if we just want to try out some commands in a repl 0 is usually fine. To give a full sense of what is actually happening though look at the following:

$ perl -d -e '$a = 7;'

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

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

main::(-e:1): $a = 7;
DB<1> x $a

0 undef
DB<2> s

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> x $a
0 7

DB<3> $b = $a * 9;

DB<4> print "B!" if($b > $a);
B!

What just happened? Well, the code $a = 7; was passed to the debugger but not executed. With the debugger command x $a we see that $a is undefined. The debugger command s is then given which does single step through the loaded code, in this case the loaded code is just a single line and so after that single step the debugging of the provided code is completed. We can see that $a now has the expected value. We can also then continue to execute Perl statements interactively.

Comments for this post were locked by the author