实施持久计数器

时间:2015-01-07 10:16:44

标签: perl

我想创建一种持久的计数器,但我不想使用数据库(没有其他原因,但我更愿意避免创建一个表,只有一个我不需要的计数器反正几个月) 所以我的问题是我想要计算我在函数中执行某些操作的次数,但是时间 脚本重新运行我想增加现有的数量 我想创建一个文件,只是将计数添加到文件并更新文件,但我想也许 有一个抽象准备用于这样的事情。

1 个答案:

答案 0 :(得分:3)

如果您没有在并发环境中使用计数器,

use strict;
use warnings;

sub increment {
  my ($file) = @_;
  open my $fh, "+>>", $file or die $!;

  seek($fh, 0, 0);
  my $count = <$fh> // 0;
  seek($fh, 0, 0);
  truncate($fh, 0);

  print $fh ++$count;      
  close $fh or die $!;

  return $count;
}

my $current_count = increment("/tmp/counter");