kaushal_k1 has asked for the wisdom of the Perl Monks concerning the following question:

Hi everybody, I am creating a pkg say "mypkg" which holds a global hash reference.say GLOBALVARREF. this variable is initialized to undef. once sub new on my pkg is called GLOBALVARREF starts pointing to self (blessed reference). At this point other pkgs can use this reference to fetch values from the hash. the whole thing mentioned above looks like
package mypkg; use vars qw (@ISA @EXPORT); @ISA =qw(Exporter); @EXPORT = qw( $GLOBALVARREF); our GLOBALVARREF = undef; sub new { GLOBALVARREF is intiliazed to $self. } sub get { return $someval{shift}; } pkg B; use mypkg; my $val = $GLOBALVARREF->get{'NAME'}; #my $val = $GLOBALVARREF->get{'NAME'} if defined($GLOBALVARREF)
now when i do perl -e 'use mypkg;' i get error saying can't call get on undefined value. if I put a condition saying if defined as shown in the commented line above it works fine.But the problem is "get()" gets called plenty of times in different modules.Can't add check everywhere. Is there a clean way to handle this scenario.

Replies are listed 'Best First'.
Re: GLOBAL VARIABLE HANDLING
by Corion (Patriarch) on Jul 26, 2011 at 11:53 UTC

    You never call mypkg->new(). Why do you expect initialization to happen if you never call it?

    If you want the initialization to always happen automatically, call mypkg->new() from within mypkg:

    package mypkg; use strict; sub new { ... }; ... mypkg->new(); 1;
      In pkg B instead of what i have written if i wrap that "get" call inside a function it works fine. I think there is more to it related to compile time and runtime calls which I am trying to understand.
Re: GLOBAL VARIABLE HANDLING
by Anonymous Monk on Jul 26, 2011 at 11:52 UTC
    Well, the problem with that, is the code you posted does not compile
    $ perl -e " our GLOBALVARREF = undef; " No such class GLOBALVARREF at -e line 1, near "our GLOBALVARREF" syntax error at -e line 1, near "our GLOBALVARREF =" Execution of -e aborted due to compilation errors.
      sorry but that's a sample code not meant to compile but to give a picture of what i am doing.