in reply to Using a single DBI handle in a script and a module

As per chatterbox discussions and traded /msg's, the following is a snippet of code as to how I would implement such a piece of logic:

#!/usr/bin/perl -Tw use strict; use warnings; my $dbh = self->new("DBI:mysql:database=test", undef, undef); # Reference database handle via self package # $dbh->execute("select * from users"); # ... or ... # Reference database handle methods directly from calling script # $dbh->{dbh}->do("select * from users"); exit 0; package self; use DBI; use strict; sub new { my $param = shift; my $self = {}; bless ($self, (ref($param) || $param)); $self->{dbh} = DBI->connect(@_); return $self; }; sub execute { my $self = shift; return $self->{dbh}->do(@_); }; 1; __END__

This code is fairly straight-forward in that a class self is created and returned to the calling namespace. This class can be accessed either within the class-space as per the execute method or via dereference to the included references to other classes ($self->{dbh}).

 

Ooohhh, Rob no beer function well without!