On Fri, May 31, 2002 at 08:49:30AM -0400, Pete Emerson wrote: > The following example does what is expected, i.e. prints out the word > password on its own line. > > used.pm > ------- > $password='password'; > > use.pl > ------ > #!/usr/bin/perl > > require "./used.pm"; > print "$password\n"; > > However, as soon as I turn on warnings and strict, and declare > $password: > #!/usr/bin/perl -w > use strict; > my $password; > require "./used.pm"; > print "$password\n"; > > I no longer get password printed on its own line.
The reason for this, in case you were wondering, is a mixture of scope and global variables. The $password variable declared in use.pl is a lexical variable, local to use.pl. The variable set in use.pm is the global $main::password (you don't get a warning about declaration because used.pm doesn't use strict). These are, obviously, two different variables. You can't set a lexical variable declared outside of a require'd or use'd file. I.e. you can't do what you're doing. A good reference for scoping issues is http://perl.plover.com/FAQs/Namespaces.html. > What is the proper way to push variables off to a different file? There are many ways to do it. First, you can do exactly what you're doing now, but you have to access $password as $main::password. You could also declare a package in use.pl, such as package Use, and access the variable as $Use::password. My personally preferred method is to use a module I wrote, Parse::PerlConfig, which basically evals the file you request and sticks all the variables in a hash. There are many modules like this that will parse a file and stick the variables in a hash or other data structure. Check your local CPAN for listings. > I could do a subroutine: sub Password { return 'password'; } and then call > sub Password from my main perl script, but that doesn't seem like "The > Right Way To Do It". You could do that, and if it works for what you're doing, that's the Right Way to do it. The right way is whatever works best for you, in terms of functionality, understandability, maintenance, etc. There are generally accepted practices for things, but there's almost never (never say never, y'know..) One Right Way To Do It. Michael -- Administrator www.shoebox.net Programmer, System Administrator www.gallanttech.com -- -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]