in reply to Global variables in Perl

Thinking about 'our' vs 'use vars' made me wonder: Why are you using a var in the first place?
package ConfigThisJunk; use strict; use warnings; use Exporter; our @ISA = qw( Exporter ); our @EXPORT_OK = qw( DEBUG ); use constant DEBUG => 1; 1;
use strict; use warnings; use ConfigThisJunk qw( DEBUG ); my $x = 123; print("debug: x is $x\n") if DEBUG;

Bonus: If DEBUG is false, the whole print-if is optimised away because it's a constant! (If it's true, the if part is optimised away.)

If you wanted the be able to change DEBUG, this is still cleaner:

package ConfigThisJunk; use strict; use warnings; use Exporter; our @ISA = qw( Exporter ); our @EXPORT_OK = qw( DEBUG ); my $DEBUG = 1; sub DEBUG { if (@_) { $DEBUG = shift; } return $DEBUG; } 1;
use strict; use warnings; use ConfigThisJunk qw( DEBUG ); my $x = 123; print("debug: x is $x\n") if DEBUG;

Replies are listed 'Best First'.
Re^2: Global variables in Perl
by taioba (Acolyte) on Jun 04, 2010 at 16:33 UTC

    Thanks, ikegami! I guess the issue is with my installation of Perl. If I use DEBUG, it croaks at the use of a bareword when strict 'subs' is in use. I had tried 'use constant', before, it kept warning me that the subroutine DEBUG was re-defined somewhere, now the warning went away. But the idea of using a sub instead of a variable is indeed neat, as Ronald pointed out. I tried &DEBUG but it looks for main::DEBUG. I'll probably just declare $DEBUG lexically in all scripts and modules and assign the function stored in ConfigThisJunk.pm to that variable. Later, I'll switch to a Mac... Cheers!

      Please stop making claims about the code that's been posted based on different code that wasn't posted.

      If I use DEBUG, it croaks at the use of a bareword when strict 'subs' is in use.

      I don't believe you, not if you import the symbol as shown in both your code and my code.

      I tried &DEBUG but it looks for main::DEBUG.

      You must not have imported the symbol as shown.

      I'll probably just declare $DEBUG lexically in all scripts and modules and assign the function stored in ConfigThisJunk.pm to that variable

      That's silly. Just use the function. Import it as shown if you don't want to use the full name.

        Well, I actually copied and pasted your code and still got those errors. I updated Exporter and even tried to use Exporter::Lite and got the same thing. If I try 'use strict qw(vars refs)' for instance, it warns 'Bareword found in conditional...' but it works fine aside from that. I'll try to run it in a Unix based machine and see what happens. At any rate, many thanks!