in reply to Overriding Global Variables

There are several ways to do this, and which ones are best depends a bit on what you're trying to do - normally, a "debug" flag is a global thing, enabled only once by a command line option or environment variable. I'm not sure why you need multiple packages to access it - will the flag be switched on and off during the run of your program? If so, a different design is probably better, because otherwise you may run into issues with the dynamic scope of the setting. To implement only what you've asked so far, I'd suggest to just have a single variable and access it in the Debug package via $Debug::.

use warnings; use strict; { package Debug; use Exporter 'import'; our @EXPORT = qw/debug/; our $FLAG = 0; # package variable sub debug { if ($FLAG) { print @_; } } } { package Foo; Debug->import; # normally "use Debug;" $Debug::FLAG = 1; # global enable debug("Hello\n"); # prints "Hello" } { package Bar; Debug->import; # normally "use Debug;" $Debug::FLAG = 0; # global disable debug("World!\n"); # doesn't print }

Replies are listed 'Best First'.
Re^2: Overriding Global Variables
by Mano_Man (Acolyte) on Nov 19, 2017 at 15:53 UTC

    Hi haukex,

    The idea was that the "debug" function is enabled or disabled in accordance to the module that uses it, effectively enabling a clean and easy way to debug different modules as part of a very large flow, involving many. One "debug" variable doesn't suit this purpose, and also adds in the clutter of setting and resetting the variable whenever needed.

      > clutter of setting and resetting the variable whenever needed.

      That's where you use local to change the flag.

      The old value will be reset automatically after the dynamic (runtime) scope is left.

      edit

      FWIW you could additionally have a lexical variable with my which is block scoped and check it using PadWalker

      You need to decide which flag takes precedence though, I'd say my over our

      Cheers Rolf
      (addicted to the Perl Programming Language and ☆☆☆☆ :)
      Je suis Charlie!

      the "debug" function is enabled or disabled in accordance to the module that uses it

      I see, in that case I would concur with karlgoethebier and I think an OO approach is probably best - each module can get an object with an individual debug flag. And looking into existing logging modules, as 1nickt said, makes sense before you re-invent that wheel.