Home > OS >  How to concat and add value in a CSV wih perl script?
How to concat and add value in a CSV wih perl script?

Time:01-10

My csv file has two columns: first name, last name :

John,DOE

I would like to add two additional columns, one of which includes the two previous columns with a perl script for the name and the other which adds the gender :

John, Doe, John DOE, man

I use other method like zapier for transform csv before import but it doesn't work.

CodePudding user response:

you have prepared library: https://metacpan.org/pod/Text::CSV lib documentation has got some examples. CSV text format file is not hard defined, this haven't got common format. Then you have defined some additional properties for it. Then, using this library, you can load all file to internal perl structure, modify this and finally save. Library will do all work, including separate field, adding quotation and escaping if it is needed. On CPAN you have child module, that simplify operations: https://metacpan.org/pod/Text::CSV::Simple

Yousually modules you should have in linux distributions with typical packaging. Otherwise (sometimes it occurs), module is not packaged, then you schould use cpan command, for manually adding lib to perl.

fun fact, on CPAN (maybe with standard linux distro packaging) is available module: https://metacpan.org/pod/DBD::CSV this module implements using CSV file like a database, but backend with CSV file. Of course, there are available many more backends, like MS SQL, Postgres, MySQL, SQLite, and ..... XLS :) and many more. But scripting with database approach is a bit more complicated.

CodePudding user response:

For this short string manipulation, you would do something like this:

use strict;
use warnings;

my $str = "John,DOE";                   # simulating reading from input
# chomp $str;                           # uncomment if you are reading csv from file
my ($fname, $lname) = split /,/, $str;  # get names
my $gender = "man";                     # determine gender 
$str = join ',', $str, "$fname $lname", $gender;
print "$str\n";                         # adding newline (back)

Output:

John,DOE,John DOE,man

Note that in order to add spaces like in your requested output, you would have to break the csv format (? Or maybe it is allowed), and it seems to be mostly for human readability purposes. So fix that if you need that.

If this is a production code issue, you probably should use Text::CSV or similar csv parser to avoid risking damage to your csv. That does not seem to be what you are after, and it does complicate your question somewhat. There is a nice synopsis to read for how to use it.

  • Related