in reply to Re^2: Formatting question??
in thread Formatting question??

still the same errors. Fetch returns a scalar reference, not a list, and don't fetch within the fetch on the same handle

my $csv = Text::CSV_XS->new ({ binary => 1, eol => "\r\n" }); # First print the Header row $csv->print (*STDOUT, $_read_sth->{NAME}); # Then show all records # v---! while (my $row = $_read_sth->fetchall_arrayref) { $csv->print (*STDOUT, $row); }

Enjoy, Have FUN! H.Merijn

Replies are listed 'Best First'.
Re^4: Formatting question??
by sudip_dg77 (Novice) on Apr 14, 2008 at 15:38 UTC
    Thanks for you lines of code.

    I have modified my lines of code as follows:

    my $csv = Text::CSV_XS->new ({ binary => 1, eol => "\r\n" }); $csv->print (*STDOUT, $_read_sth->{NAME}); while (my $row = $_read_sth->fetchall_arrayref) { ##Do I need the Dumper function here? as I am supposed to print + multiple resultsets and each has a different heading? $csv->print (*STDOUT, $row); }
    But it is returning me the following error :

    Expected fields to be an array ref at /cluster/uapp/app/bin/mytest.pl + line 58. ##Line 58 is this one-->> " $csv->print (*STDOUT, $_read_sth->{NAME} +);


      This took me a while, and brought me to some new dark corners of XS code :)

      No, you do not need Dumper. In fact, you should never need Dumper. Data::Dumper is for debugging, not for production code. But that aside. The code I showed you should have worked from the perl side of view. $sth->{NAME_lc} returns a reference to a list, but in this case, as it is a statement handle from DBI, it is not a plain reference, but a reference with magig attached, and Text::CSV_XS cannot deal with that (yet). So the solution might be:

      $csv->print (*STDOUT, [@{$sth->{NAME_lc}}]);

      Which dereferences the reference to a list, and puting it back in an anonymous array again. That line would deserve some comment in production code :)

      So, your final code should look like this:

      my $csv = Text::CSV_XS->new ({ binary => 1, eol => "\r\n" }); $csv->print (*STDOUT, [@{$_read_sth->{NAME}}]); while (my $row = $_read_sth->fetchall_arrayref) { # If you need to add other headers ... $csv->print (*STDOUT, [qw( some different header )]) if $needed; # print the data fetched $csv->print (*STDOUT, $row); }

      Enjoy, Have FUN! H.Merijn

      I've now fixed this for the upcoming 0.42, which also accepts arra-refs with magic.

      Meanwhile, I learned that arra-refs with magig have some other magical behaviour too, so that:

      $csv->print (*STDOUT, \@{$sth->{NAME_lc}});

      also works. Personally I find this a bit counter-intuitive. The next release will support

      $csv->print (*STDOUT, $sth->{NAME_lc});

      If you can't wait for the official release, get it here.


      Enjoy, Have FUN! H.Merijn