|Perl: the Markov chain saw
Re: How to import "global" variables into sub-scripts from main script?by jcb (Parson)
|on Mar 22, 2021 at 22:52 UTC
As my fellow monks have mentioned, our creates a lexical alias to a global variable. Since you are not using packages, all of your code is ending up (implicitly) in package main.
In the absence of any package statements, our $DEBUG; declares a lexical alias $DEBUG in the current lexical scope for the global variable $main::DEBUG (or $::DEBUG since main has a special alias at the empty name). That global variable still exists for other lexical scopes, which is why your code worked correctly without strict in the sub-scripts.
Note that our declares a lexical alias and optionally sets a value for the aliased global. Using our $DEBUG = 1; both declares the alias I described above and sets $DEBUG to 1. Using only our $DEBUG; only declares the alias and does not change the value at all. Since the alias aliases a global variable, that variable will still have whatever value it was previously given. This is different from my $var, which creates a new and different $var each time it is used. In all cases, a variable that has never been assigned reads as an undefined value.
In brief, since you are not using packages, all you need to do is add "our $DEBUG;" to each of your sub-scripts (and similar lines for other our variables that you want to "import" from the main script). The variables already exist in Perl's symbol table, you only need to create new lexical aliases to them.
Lastly, this also means that if your sub-scripts have any variables that are not used in other files or the main script, you can declare them with my in the sub-script, and each sub-script can have its own variable, even if two sub-scripts have different my variables with the same name.