in reply to using main package variables within a module

You may find some answers in Coping with Scoping.

That being said, I really think it's a bad idea for your package to try and access variables in main. If a sub in another package needs some information, then pass it to the sub.

One the last line of your test.pl file, what would be the harm in calling your sub like so:

Shop::db_connect( \%conf ) ;

And then changing your Shop_db_connect function to read:

sub db_connect { my $conf = shift ; print "Print - ", $conf->{'db_database'}, " - from the Shop package\n"; }

I don't know if you are able to access your main varables the way you're trying to, but if you can, you may be leaving the door open for unexpected side effects with your variables in main. If a sub, any sub, needs something that's not supposed to be global, then just give it to it. Don't expect it to come get it itself. If you need the sub to be able to change values you give it, pass them by reference like so:

#! /usr/bin/perl use strict ; use Data::Dumper ; my %conf = ( DB_NAME => 'DB01' ) ; pass_by_reference( \%conf ) ; print Dumper( \%conf ) ; sub pass_by_reference { my $conf = shift ; $conf->{DB_NAME} = 'DB03' ; }

Even this can be a little messy, because from the calling package there's no way to know what's happening to %conf. But, it's a whole lot cleaner than accessing global variables.


_______________
D a m n D i r t y A p e
Home Node | Email

Replies are listed 'Best First'.
Re: Re: using main package variables within a module
by fireartist (Chaplain) on Jun 17, 2002 at 20:19 UTC
    Rest assured that the only reason I had that dirty $one in global was because I stripped the script to the bare minimum to try and figure out what was going wrong.

    The only globals the entire script has are $dbh, $sth, $rc for database calls, and $conf and %conf.
    $conf contains the hash from my config file and %conf is my CGI params grabbed from CGI->vars.

    I think for now I'm going to experiment with both cLive ;-)'s suggestion of containing my config data in a module of it's own, and I think I'll also try out setting the $conf reference to a global.
    my $main::conf; unless ($::conf = do ('/home/4220/straitwa/www.straitway.net/shop_34/c +on +f.pl')) { die ("Could not open config file"); }
    I'd appreciate anybody's opinion on whether having five global variables is a bad thing. - I mean, should I really aim to have no globals or is that overkill.

    I realise that my whole problem here was my misunderstanding that my $foo declared in the main package doesn't make it the same as $main::foo
    I greatly appreciate everyone's help here,
    Thanks!

    fireartist