On 2/20/06, The Ghost <[EMAIL PROTECTED]> wrote: > I have defined $dbh (a database handle) as a global variable. I have > a module, RD, that needs access to the database. How can I use $dbh > within the RD module? >
The best way to handle this is to create a singleton object to hold the database connection instead of using a global variable. First create a module named Project::DB::Handle. package Project::DB::Handle; our $dbh; use DBI; sub new { return $dbh if $dbh; $dbh = DBI->connect(...); } Then in any part of your code where you use the database handle you can say sub foo { my ($foo, $bar) = @_; my $dbh = Project::DB::Handle->new; my $sth = $dbh->prepare(...); #etc. } If you want to get fancy then you can create parameters to the new function to control which DB connection is returned like this (using the DSN as the parameter): package Project::DB::Handle; our %dbh; use DBI; sub new { my $db = shift; return $dbh{$db} if $dbh{$db}; $dbh{$db} = DBI->connect($db, ...); } -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] <http://learn.perl.org/> <http://learn.perl.org/first-response>