perl: globals and a package.

I am still learning perl and confused on this script I am revising at work. The original author uses a package, which I have left in the code; however, I cannot seem to access the global variable $dir.

Code snippet:

I have also tried using $RRD_MG::dir to no avail.

Thank you.

Is $dir really global? Try removing the my definition. I may be wrong, but doesnt "my" reduce the scope of a variable? You may be inadvertantly reducing the scope of your $dir to a file (or sub routine) by using the "my" keyword. Try removing it.

google,

When omitting the "my" I get the following:

Global symbol "$dir" requires explicit package name at mg_perl_routines.pl line 9.

I have tried using the package notation, as well as the "our" keyword. I am looking at a few books which have examples, but I have yet to understand this package stuff with perl :eek:

Either you use

(1)

my $dir = 'compdata';

Or (2)

$RRD_MG::dir = 'compdata';
[...]
open SA, ">${RRD_MG::dir}/$pg";

There is NO such thing as

my $RRD_MG::dir

as package global is a separate concept from lexicals.

Of course, because "use strict" exists in the package, you need to make sure all references to package globals are qualified by the package name, so we need to put the package name in the open() statement above also, even though we refer to package globals in the same package we are currently in, which is implicitly assumed if "no strict" is in effect.

our() is a nice way to avoid this qualification in strict mode, though. But IMO I prefer qualifying package names explicitly always (if I want to go "strict") to make a visually clear distinction from lexicals (declared with "my"), which do not take any package qualifiers. Also, I think our() was only available since Perl 5.6 so servers whose perl version is out of date may not use this declaration.

Thanks cbk, but I'm still having trouble :confused:

If I change the variable declaration to $RRD_MG::dir = 'compdata'; and leave the variables as $dir within the sub, I get
Variable "$dir" is not imported at (eval 661) line 26.

Now, if I change the $dir within the functions to ${RRD_MG::dir}, as you suggested, I do not get any errors, but I also do not get any output. The code works properly if I place my $dir = 'compdata'; inside of each sub.

I'll get this package stuff yet...

I've narrowed the problem down. If I modify the script to be standalone, it functions correctly. The problem lies in the fact that it is being called within a typesetting program.

Problem solved. The way the script had to be called from the system was on a subroutine basis. Once I grasped this, I copied what the original programmer had done and I put $dir into the get_env sub like so:

Thank you for your help google and cbk.:slight_smile:

What a great feeling it is to fix a program on your own albeit with a little direction from your friends! Good work.