in reply to DBI: $dbh-disconnect; yes, now, now, but not now!
For each of your individual subroutines, you can define a private subroutine that actually does the work, plus a public subroutine that gets the database handle, calls the private subroutine, and then disconnects. For example:
sub make_report1 { my $dbh = &_get_dbh; &_do_make_report($dbh); $dbh->disconnect; 1; } sub _do_make_report { my $dbh = shift; ## etc... } sub make_all_reports { # connect to the database my $dbh = &_get_dbh; &_do_make_summary_report($dbh); &_do_make_report1($dbh); &_do_make_report1($dbh); ... # close the database connection $dbh->disconnect; # return happy and healthy return (1); }
If you get tired of writing the stub subroutines, you could autogenerate them with autoload. This would add some overhead. Namely, you could define an autoload subroutine like this one:
That way, you could just define your _do_* subroutines, and the public versions would be autogenerated the first time they are called.package your_package; sub AUTOLOAD { no strict qw(refs); our $AUTOLOAD; $AUTOLOAD =~ m{ (.*) :: (.*?) $ }x; my $dispatch_name = "$1::_do_$2"; if (defined &{$dispatch_name}) { *$AUTOLOAD = sub { my $dbh = &_get_dbh; my $rc = &$dispatch_name(@_); $dbh->disconnect(); return $rc; }; goto &$AUTOLOAD; } else { croak("Unable to autogenerate method for '$AUTOLOAD': no such +function '$dispatch_name'"); } }
On the other hand, Masem's point (and others) are well taken. You can avoid doing all of the above by having your _get_dbh function work like so:
$your_package::DBH = undef; sub _get_dbh() { defined($your_package::DBH) and return $your_package::DBH; $your_package::DBH = DBI->connect... return $your_package::DBH; }
Update: Added autoload section.
Update: Added "on the other hand..."
stephen
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Re: DBI: $dbh-disconnect; yes, now, now, but not now!
by DeaconBlues (Monk) on Mar 15, 2001 at 21:19 UTC |