C programmers often include debugging code in #ifdef DEBUG / #endif sections. By compiling with -DDEBUG the code gets included, otherwise it's left out. So the debugging code can be (and often is) left in, for future use.

WIBNI you could do the same in Perl? Source filters (see Filter and Filter::Simple) can obviously do the same; the Filter distribution even includes an example of doing this.

Here's a lighter-weight version. Unfortunately, it does leave an empty sub when debugging is disabled.

Usage

Save the snippet in a file Debug.pm and stow the file somewhere useable.

Add use Debug (1); to the start of your code. Put debugging code in a block, preceded by DEBUG:

use Debug (1); print "This is the program\n"; DEBUG { print "Debugging mode is ON\n"; }; print "Program continues...\n";
To turn off the debugging portions, chance "use Debug (1)" to plain "use Debug".

If you need more than one type of debugging block, add another argument to use Debug:

use Debug (1); use Debug (0, DBG_SPECIAL); DEBUG { warn "First type\n"; }; DBG_SPECIAL { warn "Second type\n"; }
# This goes in Debug.pm... package Debug; use strict; sub doit (&) { my $cref = shift; $cref->(); } sub dontdoit (&) {} # Export appropriate one as DEBUG sub import { shift; my $package = caller || ''; my $name = $_[1] || 'DEBUG'; { no strict 'refs'; * { "${package}::$name" } = (@_ && $_[0]) ? \&doit : \&dontdoit; } } 1;

In reply to Conditionally executing debugging code by ariels

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.