Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses

Accessing DEBUG constant from sub-package

by Anonymous Monk
on Aug 09, 2013 at 23:21 UTC ( #1048862=perlquestion: print w/replies, xml ) Need Help??

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

In my main script I set up the debug constant like so:
my $debug; BEGIN { GetOptions('debug|d' => \$debug) or die } use constant DEBUG => $ENV{DEBUG} || $debug;
Then I instantiate a object from a different package:
use Thing; my $obj = Thing->new;
I want the $obj to know when it should be in debug mode (the debug value won't change during the script run), but don't want to pass it in as a variable, because then the compiler can't optimize away the debug code. The only way I see to do this is to do this in the Thing package:
use constant DEBUG => &main::DEBUG;
This doesn't seem very clean. Is there a better way to deal with this, or is it a case of having your optimization and eating it too?

Replies are listed 'Best First'.
Re: Accessing DEBUG constant from sub-package
by BrowserUk (Patriarch) on Aug 09, 2013 at 23:49 UTC

    Define the debug code in your modules in terms of ::DEBUG. Ie:

    package Some::Thing; ... if( ::DEBUG ) { ## do debug stuff }

    And in main:

    use constant DEBUG => 1; ## set to 0 to disable debug and have debug g +uarded code optimised away use Some::Thing; ...

    With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.
Re: Accessing DEBUG constant from sub-package
by tobyink (Canon) on Aug 10, 2013 at 07:06 UTC

    Personally I'd do something like this in the Thing package:

    use constant DEBUG => main->can("DEBUG") && main->DEBUG;

    This makes your Thing package more re-usable, allowing it to be used in scripts that don't define a DEBUG constant in the main package.

    package Cow { use Moo; has name => (is => 'lazy', default => sub { 'Mooington' }) } say Cow->new->name

Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://1048862]
Approved by BrowserUk
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others chanting in the Monastery: (2)
As of 2022-01-16 18:58 GMT
Find Nodes?
    Voting Booth?
    In 2022, my preferred method to securely store passwords is:

    Results (49 votes). Check out past polls.