Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it proper to get and especially set Perl module's global variables directly?

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).

like image 583
DVK Avatar asked May 27 '10 16:05

DVK


People also ask

How do I declare a global variable in Perl?

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.

What is the difference between my and our in Perl?

my is used for local variables, whereas our is used for global variables.

What is use vars in Perl?

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.

In which block you can modify $? To change the exit value of the program?

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.


1 Answers

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.

like image 173
Michael Carman Avatar answered Jan 04 '23 17:01

Michael Carman