open (RECORD_NUMBER, "counter_data.dat") or die;
With 2-argument open, not specifiying the open mode, you open the file for input only. Either open it for input, best done explicitly with 3-argument open, close it after reading, re-open it in write mode then - or open it for update. for die see below.
$count = <RECORD_NUMBER>;
The line you just read might contain a line feed character at the end. Use chomp: chomp($count = <RECORD_NUMBER>);
$count = $count + 1;
Better written as $count++; - see perlop.
print RECORD_NUMBER "$count";
Useless variable interpolation within double quotes. print RECORD_NUMBER $count; is just fine. But then, you might want to append a "\n".
close (RECORD_NUMBER) or die;
Big plus for checking the return value of close. It's rarely seen, but should be done on every close. You might say or die "Can't close filehandle RECORD_NUMBER: $!\n" - so you know what went wrong.
I would write your code probably as
open (RECORD_NUMBER, '+<', "counter_data.dat") or die; chomp($count = <RECORD_NUMBER>); $count++; seek RECORD_NUMBER, 0, 0; print RECORD_NUMBER $count,"\n"; close (RECORD_NUMBER) or die "Canīt close filehandle RECORD_NUMBER: $! +\n";
The seek call rewinds the file to the beginning. If I did not, the new number would just be written at the actual file position - after the line read in.
--shmem
_($_=" "x(1<<5)."?\n".q·/)Oo. G°\ /
/\_¯/(q /
---------------------------- \__(m.====·.(_("always off the crowd"))."·
");sub _{s./.($e="'Itrs `mnsgdq Gdbj O`qkdq")=~y/"-y/#-z/;$e.e && print}
In reply to Re: File I/O
by shmem
in thread File I/O
by Anonymous Monk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |