Tech_20
asked on
Add additional column to .csv using Perl.
I have a Perl script written to extract the 3rd column out of a beginning .csv file and then to place that content into a new .csv file. Now I want to take the 7th column from the original file (test.csv), add a column to new file and then input that 7th column data.
I have tested this using the splice command but only get the first column in output. Please refer to the attachment. Thanks.
textCSV.txt
I have tested this using the splice command but only get the first column in output. Please refer to the attachment. Thanks.
textCSV.txt
ASKER
I included a sample .csv. The first block of code (while loop) takes the 3rd column and creates a new .csv with that column in it. I want the 7th column to be in the 2nd column of the new .csv.
In other words, I want to go from this
252 989 charlesID# ROOM# SUITE# ZIP CODE BUILDING#
333 343 jamesID# ROOM# SUITE# ZIP CODE BUILDING#
to this....
charlesID# BUILDING#
jamesID# BUILDING#
I hope that clear things up. Thanks.
sample.csv
In other words, I want to go from this
252 989 charlesID# ROOM# SUITE# ZIP CODE BUILDING#
333 343 jamesID# ROOM# SUITE# ZIP CODE BUILDING#
to this....
charlesID# BUILDING#
jamesID# BUILDING#
I hope that clear things up. Thanks.
sample.csv
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Oops. That should be $fields->[6] (not $fields->[7]) in my code (I copied that mistake from the original code).
ASKER
Thanks. I tried the code (ID: 41371906, wilcoxon). I'm having trouble with the perl module Text::CSV on OS X. I get the following error after reinstalling the module several times. Please see attached file. Any advice?
cpan_error.txt
cpan_error.txt
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Both wilcoxon and ozo had the "Best Solution" with their scripts but I could only choose one (which was entered first). Equal points for both scripts and some for the module advice. Thank you both so much!
The first while loop goes until $csv->getline ($data) is false, which means it is false at start of the next while loop so the second while loop is never entered.
If the second while loop had been entered, the splice would insert the field at position 7 into position 2, which would change
0, 1, 2, 3, 4, 5, 6, 7, 8, 9
into
0, 1, 7, 2, 3, 4, 5, 6, 7, 8, 9
it would then print the new position 7, which would be the 6 which was shifted down one position