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

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/


Reply via email to