<?xml version="1.0" encoding="windows-1252"?>
<node id="316353" title="Invoking the debugger on yourself" created="2003-12-22 05:00:30" updated="2005-08-13 12:55:16">
<type id="1980">
snippet</type>
<author id="29008">
grinder</author>
<data>
<field name="doctext">
</field>
<field name="snippetdesc">
&lt;p&gt;I needed to run the debugger on a long-running process, and the conditional breakpoint required was too hairy for my poor brain to figure out. After a bit of spelunking in &lt;tt&gt;perldoc perldebug&lt;/tt&gt; and &lt;tt&gt;perldoc DB&lt;/tt&gt; I came up with the code below.&lt;/p&gt;

&lt;p&gt;There are a few things to be aware of:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Note the &lt;tt&gt;-d&lt;/tt&gt; switch on the shebang line. This will run the program under the debugger.&lt;/li&gt;
&lt;li&gt;Using &lt;tt&gt;-d&lt;/tt&gt; will by default stop execution at the first executable statement. To start the program immediately without have to wait for a person to hit the 'r' key and press enter, the environment variable &lt;tt&gt;PERLDB_OPTS&lt;/tt&gt; should be set to &lt;tt&gt;nonstop&lt;/tt&gt;. Hence, in a Bournish shell, the program should be run with &lt;tt&gt;PERLDB_OPTS=nonstop myprogram myarg1 myarg2...&lt;/tt&gt;
&lt;/li&gt;
&lt;li&gt;Setting &lt;tt&gt;$DB::single&lt;/tt&gt; to 1 will cause the debugger to take over control at the beginning of the next statement. The documentation warns that this variable should be considered read-only, but setting it doesn't appear to have any ill effects that I could see.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;In my real-life example, the setting of $DB::single involved opening sockets to remote machine and database lookups, but in essence was doing nothing more than the example below. It might make more sense to say &lt;tt&gt;$DB::single = maybe_breakpoint($foo, $bar, $rat,...)&lt;/tt&gt; and encapsulate the mess in a subroutine.&lt;/p&gt;
&lt;p&gt;Also note that XML::SAX::PurePerl is really, &lt;b&gt;really&lt;/b&gt; slow under the debugger. Do not adjust your terminal, it will respond... eventually &lt;tt&gt;:)&lt;/tt&gt;&lt;/p&gt;</field>
<field name="snippetcode">
&lt;CODE&gt;
#! /usr/bin/perl -wd

use strict;

for my $step( 0..9 ) {
        print "$step\n";
        $DB::single = 1 if $step == 5;
}
&lt;/CODE&gt;</field>
</data>
</node>
