Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

Re: Re: using main package variables within a module

by fireartist (Chaplain)
on Jun 17, 2002 at 16:15 UTC ( #175118=note: print w/replies, xml ) Need Help??


in reply to Re: using main package variables within a module
in thread using main package variables within a module

I don't like it either ;)

I'm really wanting to understand why my $one isn't working, I think it's in scope!

As I explained above, I'll also be wanting to access variables from my config file - something like below, expect this doesn't work.

test.pl
#!/usr/bin/perl -wT use strict; use lib '/home/4220/straitwa/www.straitway.net/shop_34/lib'; use Shop; my ($conf); #open the config file and parse it unless ($conf = do ('/home/4220/straitwa/www.straitway.net/shop_34/con +f.pl')) { die ("Could not open config file"); } Shop::db_connect;
Shop.pm
package Shop; use strict; use Exporter; use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS); $VERSION = 1.00; @ISA = qw(Exporter); @EXPORT = (); @EXPORT_OK = qw(db_connect); sub db_connect { print $conf->{'db_database'}; } 1;
conf.pl
{ db_database => 'straitway_1', }
What I'm wanting is the module Shop.pm to use the data in conf.pl, but I'm getting the error message
Global symbol "$conf" requires explicit package name at /home/4220/str +aitwa/www.straitway.net/shop_34/lib/Shop.pm line 13. Compilation failed in require at ./test.pl line 4. BEGIN failed--compilation aborted at ./test.pl line 4.

Replies are listed 'Best First'.
Re: Re: Re: using main package variables within a module
by mfriedman (Monk) on Jun 17, 2002 at 18:11 UTC
    I'm really wanting to understand why my $one isn't working, I think it's in scope!

    But it's not in scope. :)

    The problem you're having is because you're trying to access a lexical (my) variable outside of its lexical scope. That's a no-no. Only package variables can be accessed via their full package name.

    As an example of why this is, consider the following:

    if ($foo == 3) { my $bar = 1; } else { my $bar = 1; }

    Here you've got two distinct $bar's, each one in a different lexical block. If you said $main::bar, and Perl allowed outside access to lexicals, how would Perl know which $bar to give you? It can't. That's why $main::bar can only refer to a package global. Since you're using strict, you have to declare it with a fully qualified name. That means you'll need to call it $main::bar (or $::bar, for short) when you declare it in test.pl.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://175118]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (4)
As of 2021-07-25 17:57 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?