Quoth Wcool <>:
>
> From the chapter on internal workings of Perl in the Perl book, I
> think it should be possible to conditionally compile something based
> on a variable.
>
> I have the following real problem: my code has a lot of statements
> that conditionally print a tracing message.
> That is based on a command line parameter.
>
> Is it possible during the compilation phase to NOT generate any code
> for those statements if that command line is not set.
> Example:
>
>
> sub Trace
> {
> my ($debug, $msg) = @_;
>
> if ($debug) {
> print $msg."\n";
> }
> }
>
> sub SomeFunc1
> {
> Trace($opt_d, 'In SomeFunc1');
>
> ....
>
>
> Trace($opt_d, . 'some_var = '.$var1);
>
> ...
>
> Trace($opt_d, . 'some_var2 = '.$var2);
>
> etc
> }
>
> If opt_d is not set I like the Perl not to generate any code for it
> internally (some sort of skip)
> The compiler would go through SomeFunc1 at just don't parse the Trace
> statement.
> This would increase speed of the program (slightly).
The closest to what you are asking for (without getting into seriously
difficult stuff) is to something like this:
use constant DEBUG => $opt_d;
use Carp;
sub Trace {
my ($msg) = @_;
carp $msg; # carp will send the message to STDERR, and
# report it from the point of view of your
# caller.
}
sub SomeFunc1 {
Trace('in SomeFunc1') if DEBUG;
}
Perl will optimize out the Trace calls at compile time, since the
condition is a compile-time constant.
HOWEVER, there is a problem here: the value of $opt_d has to be known at
compile time. This means that your getopt call (or whatever) will have
to be in a BEGIN block.
Also note that the $opt_x interface to Getopt::Std (assuming that's what
you're using) is a bad idea. It's much better to pass getopt a hash to
put the options in.
Ben
|