Breaking into the debugger programatically with Perl


In some situations you might wish to programatically stop the execution of a script if a debugger is attached. Some use-case scenarios:

  • You are debugging an area of the code which gets frequently executed (in a loop for example), but you are only interested to see its status under certain conditions
  • You have a central place for error handling (for example a log_error type routine) and you wish to be alerted during debugging if it is called (because it means that possibly there was an error and you would like to examine it live – the stack trace, variable, etc)

This can be done the following way:

$break_debugger = $^P;
# ...
$DB::single = 1 if ($break_debugger);

What does this code do? First, it uses a variable to enable/disable this feature. This can be useful if during the debugging session you decide that you don’t want to be alerted any more (you simply eval the expression $break_debugger = ). The $^P predefined variable is set when a debugger is attached, and not set otherwise, providing a good default value for the flag.

One final note: this code breaks at the next line of code after it (actually, as I understand it, it puts the debugger in single step mode, which is checked before executing each line). This means that if this is the last line in a subroutine, the break will occur at the next line after you return from it (at its caller, or at its caller’s caller, etc). If you wish to examine the stack / parameters / etc, take care to not to place it on the last line of the subroutine.


Leave a Reply

Your email address will not be published. Required fields are marked *