Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
PerlMonks  

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 (Pope) 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?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others having an uproarious good time at the Monastery: (6)
As of 2019-11-17 23:19 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Strict and warnings: which comes first?



    Results (87 votes). Check out past polls.

    Notices?