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

In reply to Re: using main package variables within a module by DamnDirtyApe
in thread using main package variables within a module by fireartist

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.