On Mon, Feb 10, 2003 at 12:02:14PM -0500, Richard Morse wrote:

> I then have (below the end of the main program), added things like:
> 
> ....program....
> 
> package sas;
> use strict;
> use warnings;
> sub preprint {
> ...
> }
> sub dbquote {
> ...
> }

> There are certain variables that I want to use in many subprocedures in
> these various packages, so I figured that I could just write "my $TEMPDIR =
> ..." after the use warnings;, and then I'd be able to use them in the sub
> procedures.  After all -- this works when I'm not doing many packages.
> However, I can't get the value to be used!  When referenced from within a
> sub (like, say, sub dbquote), it evaluates to undef, _not_ to "c:/temp", as
> I have defined it to be.
> 
> I then tried, just for the heck of it, changing the 'my' declarations into
> 'our' declarations.  But this didn't help.
> 
> Can anyone explain what I'm doing wrong?

You haven't provided as much of the code as you should have...  :)

However, it sounds like you have one big file that looks like this:

# the main program:
my $output_type = 'sas';
$output_type->do_something();

# the packages:

package sas;
use strict;
use warnings;
my $TEMPDIR = 'c:/temp';

sub do_something {
  print "tempdir: $TEMPDIR\n";
}


Think about the order in which this program is executed:

1. $output_type is set.
2. 'sas'->do_something() is called.
3. In do_something(), the value of $TEMPDIR is printed.
4. $TEMPDIR is set.
5. The program exits.


The problem is that the variables are initialized after the calls to the
subroutines that use those variables.


There are several ways to address this issue:

Move the variable initialization to the top of the file.

Move the packages into separate files, and load them in with require or
use.

Put the variable initializtion inside a BEGIN or INIT block, e.g.:

my $TEMPDIR;
INIT { $TEMPDIR = 'c:/temp' }


HTH,
Ronald
_______________________________________________
Boston-pm mailing list
[EMAIL PROTECTED]
http://mail.pm.org/mailman/listinfo/boston-pm

Reply via email to