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

Here is an excerpt of my code:

use Tie::File; .... my @content; tie @content, 'Tie::File', $filename or die "Can not read file $file +name ($!)"; print "First Line: $content[0]\n"; print "Number of lines in file: $#content\n";

I expected to see the first line of my file printed, and the number of lines in the file, but the first print statement prints the whole file, and the second print statement says Number of lines in file: 0. I guess I have misunderstood something in the description of Tie::File. What did I do wrong?
-- 
Ronald Fischer <ynnor@mm.st>

Replies are listed 'Best First'.
Re: Can't get Tie::File working
by JavaFan (Canon) on Oct 14, 2008 at 11:47 UTC
    Try using the 'recsep' parameter when tieing the file, as in
    tie @content, 'Tie::File', $filename, recsep => "\n";
      Try using the 'recsep' parameter

      I tried this and this works (though, as a have explained in my reply to Corion, I still don't quite understand why it is necessary, since I didn't have to care about line endings when processing files in the "normal" way). Of course now I have the problem that I first need to find out what line ending style the file has before being able to tie it. Maybe it's in my case better to read the file manually into the array instead of using Tie::File, as I don't want to change anyway.

      -- 
      Ronald Fischer <ynnor@mm.st>
Re: Can't get Tie::File working
by lamp (Chaplain) on Oct 14, 2008 at 11:36 UTC
    Tie::File represents a regular text file as a Perl array. Each element in the array corresponds to a record in the file.

    So $#content will return index of the last element of '@content' array(which is one less than the length of the array, since arrays start from zero).

    Use scalar(@content) for getting the size of an array.
      $#content will return index of the last element in the array

      OK, this explains the second half of the problem. But why do I get "the whole file" slurped into $content[0]? I had expected that each line in the file is one line in the array.

      Could it have to do with line endings? The file is a Unix-Style file (\n separated), but the program is running on Windows (ActiveState Perl). But OTOH, the usual operations to read files (open() etc.) don't seem to have a problem with the different line endings...

      -- 
      Ronald Fischer <ynnor@mm.st>

        See the Tie::File documentation on recsep:

        By default, the meaning is the same as for the <...> operator: It's a string terminated by $/, which is probably "\n". (Minor exception: on DOS and Win32 systems, a 'record' is a string terminated by "\r\n".)

        So that's exactly your problem. Change recsep to \n and likely everything will "just work".