Hi all,
This is my first time dealing with CSV's in perl and I'm having some trouble. I have 2 CSV files which have the same columns. The issue I'm trying to tackle is that the first CSV file has data in a certain column that is blank in the second file. The first column is a list of filenames, and the 12th column in the file is an ID number for the corresponding file. So far, I'm taking in the first CSV file and making a hash of filenames / ID numbers. My thought was simply to read in the second file, run a match again the filenames in column 1, and then reference the hash I've created to get the ID number for that file name. Then I would write that ID number into column 12 on the second file within the same row as the filename I'm referencing. I just cant seem to work the logic to reference and then write the data. Any ideas? Thanks in advance. What I have so far for code follows:
#!/usr/bin/perl
use Text::CSV;
$file = 'testfile.csv';
my $csv = Text::CSV->new();
#Bring in our csv, parse it, and make a hash of filenames (keys) and I
+D numbers (values)
open (CSV, "<", $file) or die $!;
my @content;
%masterlist;
while (<CSV>){
next if ($. == 1);
if ($csv->parse($_)){
my @columns = $csv->fields();
$masterlist{"$columns[0]"} = "$columns[11]";
}else{
my $err = $csv->error_input;
print "Failed to parse line: $err";
}
}
close CSV;
# Invert the array twice to get rid of any duplicates that may have go
+tten into our hash
%masterlist = reverse %masterlist;
%masterlist = reverse %masterlist;
#Show us the output to make sure the keys and values are lined up corr
+ectly
foreach $key ( keys %masterlist ) {
print $key, " => ", $masterlist{$key}, "\n";
}
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.