in reply to removing debugging code at compile time ?

The way you have the code I think the easiest solution would be to change the meaning of the LVLx constants from "the ID of the level" (where most likely LVL1 == 1, LVL2 == 2, etc.) to "is the debug for this level turned on?". So that you could change your debug statements to

debug "this..." if LVL1; ... debug "that .." if LVL3;
You'd have to change the debug() subroutine to just
sub debug { print "$_\n" for @_; }
and make sure the LVLx constants are defined in time ... either by enclosing the debug level setting and constant definition in a BEGIN{} block or by doing that in a module you use on top of the program. Something like
BEGIN { ... read the levels that should be ON to %debug for (1.. $count_of_levels) { eval "sub LVL$_ () {$debug{$_}};"; } }

Replies are listed 'Best First'.
Re^2: removing debugging code at compile time ?
by rootcho (Pilgrim) on Jun 08, 2007 at 21:41 UTC
    cool...now how to push this BEGIN{} block from the MyUtil.pm to the package which is using it, so I dont repeat the same thing in every package
    Otherwise I have to do :
    debug 'this' if MyUtils::LVL1;
    which is ugly ;). Is this OK.
    ... eval "sub main::LVL$_ () {$debug{$_}}" ...

      If you define the constants in MyUtils.pm and only use them outside you do not need to do anything special. Define them any way you need and include them in the @EXPORT array. Something like

      package MyUtils; use base Exporter; our @EXPORT = qw(LVL1 LVL2 LVL3 debug); sub debug { print "$_\n" for @_; } my $count_of_levels = 3; our %debug = ( # fake initialization 1 => 1, 2 => 1, 3 => 0 ); for (1 .. $count_of_levels) { eval "sub LVL$_ () {$debug{$_}};"; } 1;
      and
      use strict; use MyUtils; print "Starting\n"; debug "blah 1" if LVL1; debug "blah 2" if LVL2; debug "blah 3" if LVL3; print "Ende\n";
      The reason you do not need to use a BEGIN block this way is that the code in MyUtils.pm outside any subroutines is evaluated before perl returns to the file containing the use statement and continues parsing it. So the LVLx constants do get defined in time.