Thanks Jeff,

It works fine now.

The problem was that this module (XYZ) module uses another module, which
again has the use statement to load XYZ. I don't know if the perl loads the
module again and might be this caused to reset the value back to 0.
When I commented the use statement of that module, it just works fine.

Thanks,
Sundeep

On 8/24/07, Jeff Pang <[EMAIL PROTECTED]> wrote:
>
> 2007/8/24, Sundeep <[EMAIL PROTECTED]>:
> > I need to have a package level variable. For that I am using the
> > following method:
> >
> > package XYZ;
> >
> > $XYZ::db_initialised = 0;
> >
> > sub init_db() {
> >      DB::init() unless $XYZ::db_initialized;
> >      $XYZ::db_initialized = 1;
> > }
> >
> > or
> >
> > package XYZ;
> >
> > my $db_initialised = 0;
> >
> > sub init_db() {
> >      DB::init() unless $db_initialized;
> >      $db_initialized = 1;
> > }
> >
> > Method 1 works fine and the database is initialized only once
> > (DB::init() is other module used by me for all db ops)
> >
> > Method 2 fails and tries to initialize database again...
> > I can't use method 1 as per company standards... and I can't
> > understand the reason why method 2 is failing...
> >
>
> I'm not sure why you said it try to initialize database again (each
> time?).
> But in method2 you made a closure,when calling method2 from out of
> package XYZ,the value of $db_initialized would be kept,and looks like
> it's a real package variable.
>
> see this test,
>
> $ cat XYZ.pm
> package XYZ;
>
> my $db_initialised = 0;
>
> sub init_db() {
>     $db_initialized ++;
>     print $db_initialized,"\n";
> }
>
> 1;
>
> $ cat xyz.pl
> use strict;
> use XYZ;
>
> XYZ::init_db;
> XYZ::init_db;
> XYZ::init_db;
>
> $ perl xyz.pl
> 1
> 2
> 3
>



-- 
~!~ Sun ~!~  { Its simple to be happy. But its difficult to be simple}

Reply via email to