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

i want to create a class that gets data from a database on some method call like 'get_data' or something. however, i would like to only have to initialize the database once, so is there something like a 'static' variable in java that i could use? something like:
my static $dbh
and use that if it's not null, or initialize it if it is, so for example
> my $ex1 = new DataSomething(); my $ex2 = new DataSomething(); $ex1->set_index( 1 ); $ex2->set_index( 2 ); # so they'll get different data $ex1->get_data(); # this would initialize the db and get the data $ex2->get_data(); # this would use the already initialized db

janitored by ybiC: Balanced <code> tags around codeblock, as per Monastery convention

Replies are listed 'Best First'.
Re: javalike static
by perrin (Chancellor) on Oct 28, 2004 at 21:36 UTC
    Well, for a database handle you could just use DBI->connect_cached(), and that's probably the best answer. For general use, static variables in perl are just globals:
    package DataSomething; our $dbh; sub get_data { $dbh ||= new_connection(); ... etc. ... }
Re: javalike static
by Happy-the-monk (Canon) on Oct 28, 2004 at 21:01 UTC

    This looks as if you are asking for a Perl Singleton?

    That hasn't got the wording right (nothing like "static") but it would work as you planned.

    Cheers, Sören

      yes... that helps alot, thanks.