PDA

View Full Version : Cross Package Global Variables


Pontifex
08-09-2007, 12:04 AM
Reading this:

http://www.perl.com/pub/a/2002/04/23/mod_perl.html?page=2


...I have either to use the fully qualified names such as $My::Config::test, which I dislike...


I should be able to do something like this:

wfs.pl


my $force = 1;


wfs_menu_function.pm


if ($wfs::force != 0) {
return 0;
}


And have the code execute properly (e.g. Return 0 after passing the 'if'). But the conditional is never evaluated to true.

I also tried this:


if ($main::force != 0) {
return 0;
}


But neither work. What gives?

--Pontifex

FishMonger
08-09-2007, 06:27 AM
You're trying to do it backwards.

You need to declare the var as a package global in wfs_menu_function.pm and export it into wfs.pl either by using Exporter or the aliasing method as shown in that article.

wfs_menu_function.pmpackage wfs_menu_function;

use strict;
use vars qw(%my_vars);

%my_vars = (
force => 1,
wind => 'gale',
);
1;


wfs.pl
#!/usr/bin/perl

use strict;
use warnings;
use lib '.';
use wfs_menu_function ();

use vars qw(%my_vars);

*my_vars = \%wfs_menu_function::my_vars;

if ($my_vars{force} != 0) {
print $my_vars{wind} and exit;
}

KevinADC
08-09-2007, 10:19 AM
vars is a bit deprecated although it still works. I think "our" is the preferred operator these days.

FishMonger
08-09-2007, 06:15 PM
I agree, using "our" would be preferred. I only used "vars" because that's what was being used in the referenced somewhat old 2002 article describing how to do this. It' also key to note that the article is talking about sharing vars between packages used in a mod_perl environment, which I doubt is what Pontifex is attempting to do. IMO, in most cases sharing global vars like this is a poor approach.

Pontifex
08-12-2007, 04:44 AM
Excellent thank you.

I would've gotten back earlier but I'm pushing to get this project done so I can start on other ideas.

Thanks for bearing with me as I learn. ^^

--Pontifex