package TiePlants; use 5.006; use strict; use warnings; use Exporter; our @ISA = qw( Exporter ); our $VERSION = '0.01'; use Carp; use DBI; my %creds = ( driver => "mysql", database => "plants", host => "localhost", username => "username", password => "password", port => "3306", ); my $dbh = DBI->connect ( "DBI:$creds{driver}:database=$creds{database};host=$creds{host};port=$creds{port}", $creds{username}, $creds{password}, ); croak "Can't connect to database: $DBI::errstr\n" unless $dbh; sub TIEHASH { my ( $class, %configs ) = @_; my $self = { LIST => {}, %configs }; croak "No table defined for tied hash\n" unless defined $self->{ table }; my $sth = $dbh->prepare( "SELECT * FROM $self->{table}" ); $sth->execute(); while ( my $result = $sth->fetchrow_hashref() ) { $self->{LIST}{ $result->{latin} } = $result->{english}; } return bless $self, $class; } sub FETCH { my ( $self, $key ) = @_; return $self->{LIST}{ $key }; } sub STORE { my ( $self, $key, $value ) = @_; $self->{LIST}{ $key } = $value; my $sth = $dbh->prepare( "SELECT * FROM $self->{table} WHERE latin=?" ); $sth->execute( $key ); if ( $sth->fetchrow_hashref() ) # there's a record there already { $sth = $dbh->prepare( "UPDATE $self->{table} SET latin=?, english=? WHERE latin=?" ); croak "Can't update new value: $DBI::errstr\n" unless $sth->execute( $key, $value, $key ); } else { $sth = $dbh->prepare( "INSERT INTO $self->{table} (latin, english) VALUES (?, ?)" ); croak "Can't store new value: $DBI::errstr\n" unless $sth->execute( $key, $value ); } } sub DELETE { my ( $self, $key ) = @_; my $sth = $dbh->prepare( "DELETE FROM $self->{table} WHERE latin=?" ); $sth->execute( $key ); return delete $self->{LIST}{ $key }; } sub CLEAR { my ( $self ) = @_; $self->DELETE( $_ ) for keys %{ $self->{LIST} }; } sub EXISTS { my ( $self, $key ) = @_; return exists $self->{LIST}{ $key }; } sub FIRSTKEY { my ( $self ) = @_; my $reset_iterator = keys %{ $self->{LIST} }; my $firstkey = each %{ $self->{LIST} }; return $firstkey; } sub NEXTKEY { my ( $self, $lastkey ) = @_; my $nextkey = each %{ $self->{LIST} }; return $nextkey; } sub UNTIE { my ( $self, $count ) = @_; $dbh->disconnect() unless $count; } sub DESTROY { my ( $self ) = @_; $dbh->disconnect(); } 1; __END__