my $csv = Text::CSV->new ({ binary => 1, auto_diag => 1, eol => $/ }); open my $fh, ">:encoding(utf8)", $filename or die "$filename: $!"; $sth = $dbh->prepare ($query) or # No need to put "'s around $query error ($q, "Problem with database call"); if ($sth->execute) { # not using RaiseError? while (my $ref = $sth->fetch) { # fetching data by ref is faster $csv->print ($fh, $ref); } }