in reply to Re: Creating .csv file with comma
in thread Creating .csv file with comma

This is a sample on how I am formatting the file:
#!/usr/bin/perl use strict; use warnings; my $number = "100"; my @data; push @data, [ '1234565', "Prototype", '"Number in address is '.$number.'. Please, Please check + your records."', ]; my $csv = Text::CSV->new ( { binary => 1, eol => "\n", quote_char => +'', } ) or die "Cannot use CSV: ".Text::CSV->error_diag (); open my $fh, >, "myfile.csv" or die "Unable to create file: $!"; $csv->print($fh, $_) for @{ $data }; close $fh;

Thank you!

Replies are listed 'Best First'.
Re^3: Creating .csv file with comma
by 1nickt (Canon) on Apr 24, 2020 at 19:33 UTC

    Hi again,

    sprintf -- essential tool for avoiding hackery with interpolation and escaping.

    push(@data, [ 1234565, 'Prototype', sprintf('Number in address is %s. Please, Please check your record +s.', $number), ]);
    (I advise always using parens with push and any function that will slurp up whatever's left on the line as args...)

    Hope this helps!


    The way forward always starts with a minimal test.
Re^3: Creating .csv file with comma
by Anonymous Monk on Apr 24, 2020 at 14:51 UTC
    I needed to fix the code to make it work and show the issue with double quotes twice.
    #!/usr/bin/perl use strict; use warnings; use Text::CSV; my $number = "100"; my @data = (); push @data, [ '1234565', "Prototype", '"Number in address is '.$number.'. Please, Please check + your records."', ]; my $data = \@data; my $csv = Text::CSV->new ( { binary => 1, eol => "\n", quote_char => +'', } ) or die "Cannot use CSV: ".Text::CSV->error_diag (); open my $fh, ">", "myfile.csv" or die "Unable to create file: $!"; $csv->print($fh, $_) for @{ $data }; close $fh;

    Sorry for that! Thanks!

      As I showed, remove the quote_char => '' option and remove the double quotes from inside the string '"Number in address is '.$number.'. Please, Please check your records."'.

        This line fixed my issue with the code:

        my $csv = Text::CSV->new ( { binary => 1, auto_diag=>2, escape_char => + "\\", eol => "\n", quote_char => '', } )


        Thanks for all the help!!
      So why do you put "1234565" and 'Prototype' in one pair of quotes each, and the third element in two pairs of quotes?

      You don't need an extra pair of quotes for the comma, that is Text::CSV's Task