Re: perl global vars in subroutines
by Abigail-II (Bishop) on Feb 16, 2004 at 16:25 UTC
|
Does anyone have suggestions on how to use global vars and perl modules.
Yes, as a general rule: don't.
I realize I can pass the vars to the subs, or just keep the code in the script (via subs)
That's the way to go!
I am using quite a few vars.
Depending on how much 'quite' is, and what the subs do, it
may be a sign you need a different breakdown in subs.
Or that you need to pass around structures (hashes, arrays, objects, references...) instead.
the code is being re-used quite often.
All the more reason to not use global variables to pass
parameters around.
Abigail
| [reply] |
Re: perl global vars in subroutines
by bear0053 (Hermit) on Feb 16, 2004 at 17:07 UTC
|
our global_1;
our global_2;
require(perl_mod.pm);
now in your perl_mod.pm you need to include:
our global_1;
our global_2;
This will allow you to use global variables across perl files. Make sure you use Strict as well. | [reply] [d/l] [select] |
|
|
As I said a long time ago, Why is 'our' good?
I've yet to see a good answer to that question.
(The original question is a sign of someone rapidly digging himself a deep, nasty hole. But I'll let someone else decide whether to write up a rant on modularity.)
| [reply] |
|
|
Well, first of all, if the perlmod.pm file starts with
package Me;, it's not going to work. The
our $global_1; in the main file will refer to
$main::global_1;, while the our $global_2;
in the module refer to $Me::global_1;.
But if you don't use a package statement, and have everything
in the main package, and you aren't using parameters to pass
arguments to subroutines, there's little reason to use
strict and our.
Abigail
| [reply] [d/l] |
Re: perl global vars in subroutines
by coreolyn (Parson) on Feb 16, 2004 at 18:09 UTC
|
This is a kludge answer in comparison to the other more esteemed monks, but I've gotten into the habit of utilizing enviornmental vars (i.e $ENV{'VAR'} )for my globals.
| [reply] [d/l] |
|
|
| [reply] |
|
|
| [reply] |
|
|
Re: perl global vars in subroutines
by vinforget (Beadle) on Feb 17, 2004 at 16:21 UTC
|
Thanks for the all the help. Very interesting discussion. It actually helped me solidify my decission to use OOP to solve this problem. Even though perl is not particularly suited for OOP I think it may help me establish a better program structure, as compared to just using subs, modules, and vars without OOP. OOP implements all these programming techniques, but allows for a more rigid framework for me to work in i.e. ideas like the scope of a variable seem to be inherent to the object/class, instead of trying to think about it too much without OOP. Thanks again.
Vince | [reply] |