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

Esteemed Monks,

Consider the following code, input file, and output:

#!/usr/local/bin/perl use strict; use Text::CSV_XS; use FileHandle; my $infile = "foo.csv"; my $IN = new FileHandle; open ( $IN, "<$infile") or die "can't read $infile: $!"; my $c = 0; my $csv = Text::CSV_XS->new( {'binary' => 1}); while ( my $cols_aref = $csv->getline( $IN ) ) { my @a = @{$cols_aref}; print "$a[0],$a[1],$a[2]\n"; $c++; # Alternative way to assure exiting loop exit if ( $c > 5 ); } exit; ## My foo.csv Fred,foo,3 Tom,bar,4 ## Output: Fred,foo,3 Tom,bar,4 ,, ,, ,, ,,

I don't understand what's happening in the while condition that prevents it from ending when it reaches EOF. Can anyone educate me?

-------------------------------------
Nothing is too wonderful to be true
-- Michael Faraday

Replies are listed 'Best First'.
Re: Concerning Text::CSV_XS getline in while loop
by jZed (Prior) on Dec 21, 2004 at 21:53 UTC
    This is one of the reasons I am proposing the new interface :-). Until then, put this at the top of the loop:

    last unless @$cols_aref;

    getline() returns an empty arrayref when it runs out of lines in the file so you need to check for an arrayref with no elements.

      getline() returns an empty arrayref when it runs out of lines in the file so you need to check for an arrayref with no elements.
      Makes sense. Oh, and thanks for the pointing getline() out to me.

      -------------------------------------
      Nothing is too wonderful to be true
      -- Michael Faraday

      Hi, I am having a simular problem, but the EOF is found if a non-ASCII character is found in the input string, like a German U or character of the same kind. Depending on the file it happens at the offending line. The input file has been produced by EXCEL and making a CSV-file from it on a Windows computer, while the PERL-script is running on a Linux machine. Kind regards, Bert Mengerink SPOORHOBBY

        My bet would be you forgot to read the documentation, and did not pass binary => 1 in the constructor:

        my $csv = Text::CSV_XS->new ({ binary => 1, auto_diag => 1 });

        Enjoy, Have FUN! H.Merijn