Re: perl


Subject: Re: perl
From: Michael Fowler (michael@shoebox.net)
Date: Wed Apr 17 2002 - 09:42:14 AKDT


On Tue, Apr 16, 2002 at 05:10:51PM -0800, Chris Hamilton wrote:
> Here are the connection parameters that I want to include in a separate
> script/module:
>
> my $serverName = "localhost";
> my $serverPort = "3306";
> my $serverUser = "johndoe";
> my $serverPass = "slick";
> my $serverDb = "DBName";
> my $serverTabl = "TableName";
>
> That's it. When I use "require" to try and include a script containing the
> info above, I get nothing (no errors or anything, just the html stuff).

The reason it's not working is because of scope. You have lexically scoped
variables there, and the end of scope is the end of the file you've
required. So when you go to try and use the variables, they're not in
scope, and thus don't exist.

Scoping can be a difficult concept to grasp without the proper description.
I'd suggest reading the article http://perl.plover.com/FAQs/Namespaces.html.
Even if you already understand scoping, you should probably see that
article, as it's written well.

So, making the variables package globals, placing them into their own
package, or just leaving them in main, would solve your problem. For
example:

>> connection-params.pl
    $serverName = 'localhost';
    $serverPort = 3306;
    ...

Because you haven't declared them with my, they are package globals in
main.

However, assuming you are using strict (you -are- using strict, aren't you?)
you'll either need to declare them in the calling package (with use vars or
our):

    use vars qw($serverName);
    require "connection-params.pl";

    print $serverName;

or fully qualify them:

    require "connection-params.pl";
    print $main::serverName;

This can get somewhat complex for the beginner, which is why you might
consider moving to a configuration file, instead of a library or module.
There are many configuration modules on CPAN (AppConfig, Parse::PerlConfig,
Config::IniFiles, etc.). Because there are so many it can be a little
daunting, so there's even the possibility of writing a very simple
configuration parser yourself.

Hope this helps.

Michael

--
Administrator                      www.shoebox.net
Programmer, System Administrator   www.gallanttech.com
--

--------- To unsubscribe, send email to <aklug-request@aklug.org> with 'unsubscribe' in the message body.



This archive was generated by hypermail 2a23 : Wed Apr 17 2002 - 09:42:33 AKDT