package mydb; use strict; use warnings; use Digest::MD5 qw(md5_hex); use utf8; sub new { my $class=shift; my $file=shift; return undef unless($file); my $self={}; $self->{file} =$file; $self->{table} ={}; $self->{update}=0; $self->{last} =0; bless($self,ref($class)||$class); $self->load; return $self; } sub DESTROY{ shift->save(); } sub load { my $self=shift; $self->{update}=1; return 0 unless(-f $self->{file}); if(open(my $fh, '<', $self->{file})) { while(<$fh>) { chomp; my ($name,$pass)=map{__unquote($_)}split(/#/,$_,2); next unless($name && $pass); $self->{table}->{$name}=$pass; } close($fh); $self->{update}=0; $self->{last}=-M $self->{file}; } } sub save { my $self=shift; if($self->{update} && %{$self->{table}}) { my $str=join("\n",map{__quote($_).'#'.__quote($self->{table}->{$_})}keys(%{$self->{table}})); $self->_update(); if(open(my $fh, '>', $self->{file})) { print $fh $str; close($fh); $self->{update}=0; return 1; } return 0 } return 1; } sub add { my $self=shift; my $name=shift; my $pass=shift; $self->_update(); return 0 unless($name && $pass); return 0 if(exists($self->{table}->{$name})); $self->{table}->{$name}=md5_hex($pass); $self->{update}=1; return 1; } sub del { my $self=shift; my $name=shift; $self->_update(); return 0 unless($name && exists($self->{table}->{$name})); delete($self->{table}->{$name}); $self->{update}=1; return 1; } sub has{ return exists($_[0]->{table}->{$_[1]}); } sub set { my $self=shift; my $name=shift; my $pass=shift; $self->_update(); return 0 unless($name && $pass); return 0 unless(exists($self->{table}->{$name})); $self->{table}->{$name}=md5_hex($pass); $self->{update}=1; return 1; } sub chk { my $self=shift; my $name=shift; my $pass=shift; $self->_update(); return 0 unless($name && $pass && exists($self->{table}->{$name}) && $self->{table}->{$name} eq md5_hex($pass)); return 1; } sub get { my $self=shift; my $name=shift; $self->_update(); return $self->{table}->{name} if($name && exists($self->{table}->{name})); return ''; } ######################################################################## sub _update { my $self=shift; return $self->load() if(-f $self->{file} && (!$self->{last} || -M $self->{file} != $self->{last})); return 1; } ######################################################################## sub __quote { my $str=shift; $str=~s/#/&raute;/g; return $str; } sub __unquote { my $str=shift; $str=~s/\Q&raute;/#/g; return $str; } 1;