I want to create a sort of counter that is persistent but I don't want to use the database for that (no other reason but I prefer to avoid creating a table for just having a counter which I won't need in a few months anyway).
So my problem is that I want to count how many times I do something in a function but when
the script re-runs I want to increment the existing count.
I thought to create a file and just add the count to the file and update the file but I thought perhaps
there is an abstraction ready to use for something like this.
If you're not using counter in concurrent 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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With