ねもぷらす

ふぁいんでぃんぐねもの日記。プログラミングとか育児とか

DBM 覚え書

参考:
http://www.unix.org.ua/orelly/perl/cookbook/ch14_02.htm

#!/usr/bin/perl -w
use strict;
use warnings;

use DB_File;
use Time::Local;

use constant INTERVAL => 1800; # sec
use constant DB_FILE  => './last.db';

my $debug = 1;

eval{

  # now epoch time
  my $now = time;

  # connect DB
  my %db;
  tie(%db, 'DB_File', DB_FILE)
      or die "Can't open DB_File ". DB_FILE .": $!\n";

  if( exists $db{time} && ( $now-$db{time} ) > INTERVAL ){
    # call mail_program
    print "call mail_program\n"if($debug);
    #...

    # update DB
    $db{time} = $now;

  }
  # no process
  else {
    print "not call mail_program\n" if($debug);
    print "\tnow:".&epoch_time( $now ) ."\n"if($debug);
    print "\t DB:".&epoch_time( $db{time} ) ."\n"if($debug);
  }

  # refresh `tie`
  untie %db;

};if($@){
  print "ERROR: $@\n";
}


# sub list --------------------------
sub epoch_time {
  my($epoch) = @_;
  my($ss, $mn, $hh, $dd, $mm, $yy) = localtime( $epoch );
  return sprintf("%04d-%02d-%02d %02d:%02d:%02d", $yy+1900, $mm+1, $dd, $hh, $mn, $ss);
}

1;
__END__