File Read Write Create with IO::File

Ran into an annoying gotchya with Perl’s IO::File. Apparently opening the file in append mode with read access if the file already exists puts the file position pointer at the end of the file. If it doesn’t exist, it creates the file. Note the +>>, that opens the file r/w/append. You can also use the more common (and more easily recognizable) form of a+.

    my $FH = new IO::File "$file", "+>>";
    while (my $line = $FH->getline()) {
      print "Line: $line\n";
    }
    undef $FH;

I noticed that when I tried to read the file (if it already existed), then nothing would be read. I neglected to realize that you must seek to position 0 in the file if you want to read it. Therefore the following code will work:

    my $FH = new IO::File "$file", "+>>";
    $FH->seek(0,0);
    while (my $line = $FH->getline()) {
      print "Line: $line\n";
    }
    undef $FH;

Although it might seem obvious that you need to be at the beginning of the file to read it forward (and it is), I didn’t realize the file pointer opened a file in append mode to the last position in the file (in hind sight, it does appear to be a bit more obvious).

Posted in Perl. Tags: . No Comments »