in reply to Common subs and Global Variables
If what you are doing now stops working in the future for some reason, then you can set/get my variables, i.e. local to the includee module, via setter/getter subs.
package includee; my $SHAREDVARIABLE1; sub sharedvariable1 { $SHAREDVARIABLE1 = $_[0] if defined $_[0]; $SHAREDVARIABLE1 } 1;
HOWEVER, this IMO is not good style (at least! see 5' edit below). Although it is a notch better than loose shared variables (as you propose) as it encloses the variables inside the module and you control the access via a sub which, btw, can have complex control code to limit access or, at least, log who access what via a stacktrace.
Edit after 5': there will be some edge cases which this has unexpected results. For example if another module which you include in "program.pl", includes "includee.pm" and initialises its variables. I am sure there will be more. So, not only bad style but bug-backdoor too (hey shouldn't that be "bugdoor"?). end edit.
An optimisation to this would be a package of variables, a config package, which holds all variables in, say, a hash and you access them via their keys. I am sure there will be some modules in CPAN for this purpose. Such a config class would be cumbersome in Java or C++ where you can't have mixed-type containers at will (easily and without being termed a heretic at SO). But it works well with Perl (and other dynamically-typed languages). So take advantage of this Perl feature.
The benefit of a shared-variables object is that you can pass just that object holding the state of your program into each sub which requires access to it without necessarily turning into OO.
And from that stage, perhaps elevate your "program.pl" into an OO class with all shared variables encapsulated into the class with minimal refactoring.
An added benefit of boxing all your loose shared variables into a single hash/object (OO or not) is that it makes saving and loading state (perhaps with Storable) so much more convenient, that's always a nice feature for long-running scripts.
I am a proponent of simple object-oriented programming, i.e. not to the extent of Java's maniacal bureaucracy, I like what Perl offers right now (still can't say about the "new" OO in Perl), because data encapsulation makes programming complex tasks easier, with less mistakes and bugs. Take advantage of that.
|
|---|