SPUG: Debugging methodology

Yitzchak Scott-Thoennes sthoenna at efn.org
Wed Jan 16 00:27:28 CST 2002


In article <20020115004613.A40924 at www.ladro.com>,
Chris Wilkes <cwilkes-spug at ladro.com> wrote:
>If you made Debug a constant then there wouldn't be a performance hit as
>it would get optimized away at run/compile time, if my memory of a
>recent TPJ article by Sean Burke is correct.
>
>With DEBUG => 3 then you'll have "If (3 > 0) { print }" which will get
>optimized to just "print"  Likewise if you had DEBUG => 0 the whole "if
>( 0 > 0 ) {}" will get thrown out.

Actually, it seems (on 5.6.1) to get optimized to just "do { print }",
which is slightly less efficient.

The other problem with that approach is that you can't change it mid-code
the way you can a $debug flag.  One fix would be to have something like
this at the top of your module:

our $debug;
BEGIN { *DEBUG = defined $debug ? sub () { $debug } : sub () { 0 } }

and then say in the code something like:

sub blah {
   debug_log("entering blah for $_[0]") if DEBUG;

Here, if (at the time of the 'use' of your module) there is a $module::debug
variable defined, DEBUG is a dynamic function, returning whatever the
user has currently set $module::debug to.  If not, DEBUG is a constant
0 which is optimized away.

So, if you want to debug only a particular call to method blah for a
Blah object, say:

$Blah::debug = 0;
use Blah;
...
$Blah::debug = 1;
$blah_obj->blah;
$Blah::debug = 0;

Some will be bothered by the violation of the Blah namespace by a foreign
entity.  Unfortunately, you can't have something like:

use Blah debug => 0;

since the args to use are only handled at import time, and you need $debug
set somehow before Blah.pm is compiled.  One suggestion (which I saw from
Ilya Z.) is to have a separate init module that can be used before the
module proper:

use Blah::Init debug => 0;   # sets a $Blah::debug flag
use Blah;                    # refers to $Blah::debug via BEGIN line above

 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
     POST TO: spug-list at pm.org       PROBLEMS: owner-spug-list at pm.org
      Subscriptions; Email to majordomo at pm.org:  ACTION  LIST  EMAIL
  Replace ACTION by subscribe or unsubscribe, EMAIL by your Email-address
 For daily traffic, use spug-list for LIST ;  for weekly, spug-list-digest
     Seattle Perl Users Group (SPUG) Home Page: http://zipcon.net/spug/





More information about the spug-list mailing list