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 | |
by LanX (Saint) on Nov 19, 2017 at 21:14 UTC | |
by haukex (Archbishop) on Nov 20, 2017 at 09:15 UTC |