Implement a persistent counter

I want to create a counter that is persistent, but I don't want to use a database for that (no other reason, but I prefer to avoid creating a table in order to have a counter that I won't need in a few months).
So my problem is that I want to count how many times I do something in a function, but when rerunning the script I want to increase the existing count.
I was thinking about creating a file and just adding an invoice to the file and updating the file, but I thought there might be an abstraction ready to use for something like this.

+3


source to share


1 answer


If you are not using a counter in a parallel environment,



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");

      

+3


source







All Articles