Search code examples
perlperl-module

How to use join function for creating a csv file if some fields contain additional commas


I need to write a CSV file where some of the fields contain additional commas.

So i used `my @fields = Text::ParseWords::parse_line(',', 0, $line); in order to do the processing.

But how to use join function at the end to write to a file in perl?


Solution

  • Ideally, you should use a CSV library such as Text::CSV_XS.

    If the only problem is extra commas in fields, and not extra quotes, there is a trick I will share.

    $line_out = '"'.join('","', @fields).'"'

    RFC4180 says to quote fields, i.e. "field1","field2","compound,field" , when fields may contain commas, newlines, and such.