Why isn't variable maintained between subroutines in .pm module?

F

Fred

According to the docs, if you define a variable using the
"use vars" pragma in a perl module, then that variable should
be available across the entire .pm module. Listed below I have
an excerpt from a module named test.pm. The $host variable is
defined with the "usr vars" pragma, but I can't access it from
the subroutine test() below.

Essentially what I want to do is use AppConfig to read values
from a configuration file like host, port, etc., then have
them available to other subroutines when called. I'm trying
to avoid having to read the config file every time a subroutine
is called. Is this possible without using the Storable module?

-Thanks



our @EXPORT = qw(
LoadConfig
);

our $VERSION = '0.01';

use vars qw($host $VERSION @ISA @EXPORT @EXPORT_OK);


sub LoadConfig
{
shift @_;
my ($cfgfile) = @_;

our $config = AppConfig->new(
{
CASE => 1,
PEDANTIC => 0,
CREATE => 1,
ERROR => sub {},
GLOBAL => { ARGCOUNT => ARGCOUNT_ONE }
}
);

$config->file($cfgfile);


my $host = $config->host();

#####The $host variable is assigned here
print "HOST IN LoadConfig: $host\n";

}



sub test
{

######I can't reference $host in different subroutine
print "IN TEST() HOST IS: $host\n";

}
 
G

Gunnar Hjalmarsson

Fred said:
use vars qw($host $VERSION @ISA @EXPORT @EXPORT_OK);

sub LoadConfig

my $host = $config->host();

#####The $host variable is assigned here

Yes, but that's the lexical variable $host, which is not the same as the
package global $host you declared via the "use vars" statement.

Try without "my".
 
J

Joe Smith

Fred said:
According to the docs, if you define a variable using the
"use vars" pragma in a perl module, then that variable should
be available across the entire .pm module.
True.

use vars qw($host $VERSION @ISA @EXPORT @EXPORT_OK);

This says that $host will be shared unless explicitly overridden.
sub LoadConfig
{
my $host = $config->host();

By using 'my', you have explicitly declared that, for the rest of the
sub, $host will _not_ refer to the global variable with the same name.

Remember, 'my' is exclusive with 'local', 'our', or 'use vars'.

-Joe
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,982
Messages
2,570,186
Members
46,739
Latest member
Clint8040

Latest Threads

Top