Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

File reade and recreate

by adriang (Sexton)
on Aug 20, 2014 at 07:48 UTC ( [id://1098091]=perlquestion: print w/replies, xml ) Need Help??

adriang has asked for the wisdom of the Perl Monks concerning the following question:

Hi all,

I want to create a counter using a file but this don't work

#!/usr/bin/perl use warnings; use strict; use Carp; open(my $count_file,"+<","count.txt") or croak "cant open"; my $count=<$count_file>; $count++; print $count_file $count; print $count; __END__

only this work:

#!/usr/bin/perl use warnings; use strict; use Carp; open(my $count_file,"<","count.txt") or croak "cant open"; my $count=<$count_file>; $count++; open($count_file,">","count.txt") or croak "cant open"; print $count_file $count; print $count; __END__

I want to use OPEN only once.

Thanks in advace, Adrian.

Replies are listed 'Best First'.
Re: File reade and recreate
by GrandFather (Saint) on Aug 20, 2014 at 07:58 UTC

    Add:

    seek $count_file, 0, 0;

    before the print $count_file $count; in your first version of the code.

    Perl is the programming world's equivalent of English

      Super, Thanks.

Re: File reade and recreate
by MidLifeXis (Monsignor) on Aug 20, 2014 at 13:42 UTC

    You may also want to research how to lock the file from read through write. If multiple processes have the opportunity of simultaneous execution, you have a race condition where you can get anything from the correct behavior to missing one of the updates, to corrupting the data in the file.

    In this case I don't think you have the possibility of corruption (that scenario can happen more easily on files with larger datasets), but you may miss one of the updates. ProcA starts and reads the counter. ProcB gets control, reads the counter (same value), increments, and writes the counter. ProcA now resumes, increments the (now outdated) counter, and writes it. Your counter is now one less than it should be.

    --MidLifeXis

      Thanks for the suggestion

      open($file_read,"+<","$file") or croak "cant open $file for read"; flock($file_read,2); my $count=<$file_read>; $count++; seek($file_read, 0, "0"); print $file_read $count; flock($file_read,8); close($file_read);

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://1098091]
Approved by GrandFather
Front-paged by toolic
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others chilling in the Monastery: (4)
As of 2024-04-23 16:58 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found