in reply to Re: Atomic update counter in a file
in thread Atomic update counter in a file

Then what do you suggest to atomically differentiate between creation of the file and update of the file?

Replies are listed 'Best First'.
Re^3: Atomic update counter in a file
by pbijnens (Novice) on Nov 18, 2015 at 11:43 UTC
    Answering my own question... This seems to do the trick:
    use Path::Tiny;
    #... some perl stuff
    my $FH = path(".counter")->filehandle({locked=>1, exclusive=>1}, "+>>", ":raw") or die("open .counter: $!\n");
    seek($FH,0,0);
    my $nr; { local $/; $nr = <$FH> };
    $nr ||= "000\n";
    die("garbage in .counter\n")  unless $nr =~ /^\d+\n$/;
    chomp($nr);
    ++$nr;
    truncate($FH,0);
    seek($FH,0,0);
    print $FH $nr, "\n";
    close($FH) or die("close .counter: $!\n");
    # and continuing using $nr
    
    The mode "+>>" creates the file when it does not exist yet, and allows for read and write. The "locked" and "exclusive" mode make sure we're the only one using it.