Each line needs correction ;-)
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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.