I was wondering what the best practice in Perl is regarding getting - or, more importantly, setting - a global variable of some module by directly accessing $Module::varName
in case the module didn't provide getter/setter method for it.
The reason it smells bad to me is the fact that it sort of circumvents encapsulation. Just because I can do it in Perl, I'm not entirely certain I should (assuming there actually is an alternative such as adding a getter/setter to the module).
Global variables can directly use and are accessible from every part of the program. Example 1: The variable $name is declared at the beginning of the code. It will be visible till the end of the file everywhere. Even inside blocks.
my is used for local variables, whereas our is used for global variables.
use vars qw($scalar %hash @array); This declares the named variables as package globals in the current package. They may be referred to within the same file and package with their unqualified names; and in different files/packages with their fully qualified names. With perl5.
Inside an END code block, $? contains the value that the program is going to pass to exit() . You can modify $? to change the exit value of the program.
It isn't violating encapsulation if the variable is part of the public API. (If it isn't that's another matter.)
I think direct access is preferable as it allows you to take advantage of dynamic scoping:
local $Module::varName = 42;
This makes conflicts with other code using Module
less likely.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With