use strict; use warnings 'all'; use Fcntl qw /:DEFAULT :flock :seek/; my $counter_file = "/tmp/counter"; sysopen my $fh => $counter_file, O_RDWR | O_CREAT, 0644 or die "Failed to open $counter_file: $!\n"; flock $fh => LOCK_EX or die "Failed to flock $counter_file: $!\n"; chomp (my $counter = <$fh> || 0); $counter ++; seek $fh => 0, SEEK_SET; print $fh "$counter\n" or die "Failed to write to $counter_file: $!\n"; truncate $fh => tell $fh or die "Failed to truncate $counter_file: $!\n"; close $fh or die "Failed to close $counter_file: $!\n"; ... Do whatever you want with $counter here ....