in reply to using main package variables within a module

If you change my $one to $main::one, it will work, but I don't like this solution. :)

--dda

Replies are listed 'Best First'.
Re: Re: using main package variables within a module
by fireartist (Chaplain) on Jun 17, 2002 at 16:15 UTC
    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.
      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.