package lazydbvalue; use strict; use Carp; sub TIESCALAR { # $sth is a prepared DBI statement handle my ($class, $sth) = @_; my $self = {}; $self->{sth} = $sth; bless ($self, $class); return $self; } sub FETCH { my $self = shift; $self->{sth}->execute(); my $row = $self->{sth}->fetchrow_arrayref; $self->{sth}->finish(); return $row->[0]; } sub STORE { my ($self, $sth) = @_; croak('STORE not supported - read only'); } sub DESTROY { my $self = shift; undef $self->{sth}; } package main; use strict; use DBI; # Returns the "lazy" tied scalar sub getNumUsers { my $dbh = shift; my $sth = $dbh->prepare('SELECT COUNT(*) FROM users'); tie my $numUsers, 'lazydbvalue', $sth; return $numUsers; } # Connect to DB etc., assiging connection to $dbh; my $numUsers = getNumUsers($dbh); print "Number of users: $numUsers\n"; #### sub FETCH { my $self = shift; # Just passing... if ( justPassingTheValue() ) { return $self; } # Value is being used in some expression # Now evaluate the real thing... $self->{sth}->execute(); my $row = $self->{sth}->fetchrow_arrayref; $self->{sth}->finish(); return $row->[0]; }