Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I'm using perl's -P option so that I can prevent blocks of code from being compiled by perl when I'm not debugging.

It seems to be working very well, except that I need to extend the concept to some supporting modules, which have been created with 'h2xs -X' and are using autoloader.

Basically, I want my main program to be something like:

#!/usr/local/bin/perl -P
#define DEBUG 1

Then in my module methods, I want to be allowed to do this:

#ifdef DEBUG
  &big_expensive_function();
#endif

The problem is that the c pre-processor doesn't seem to work within the modules. And the code block is being executed every single time, regardless of how DEBUG is set.

I know I could just use a perl if(). But in the end product, I'd end up processing multiple if's on the order of millions of times, and efficency is very important.

Thanks

Replies are listed 'Best First'.
Re: C pre-processor
by chromatic (Archbishop) on May 01, 2001 at 23:20 UTC
    Perl does some internal optimization. (Various meanings can be assigned to 'some', most of which are correct.)

    In particular, it can remove execution paths which will never be reached:

    chromatic$ perl -MO=Deparse print "hi"; if (0) { print "hi" } - syntax OK print 'hi!'; '???';
    If you use a constant for DEBUG and set it to 0, I'm 99.8% convinced Perl will do the right thing and not even compile the debugging code.

    Update: I just ran a test with a real Perl package, and it works. You might want to put your constant declaration in a BEGIN{} block, just to be on the safe side.

      Note. Perl's definition of "never be reached" is unaware of the possibility of being reached by goto. This is documented, so the following proves your assertion and is not a bug in Perl:
      if (0) { FOO: { print "How many times will I print?\n"; } } goto FOO;
      Note, however, that Perl will parse the code in the commented out section. If this bothers you, you can do arbitrary pre-processing through Filter::Simple. (Note that the inability to parse arbitrary Perl makes this facility substantially less useful than it could be...)