By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
437,695 Members | 1,956 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 437,695 IT Pros & Developers. It's quick & easy.

How to read csv file with multi line in one field

P: 2
I have a test.csv file with multi line in one field like following:

Name, message
"Gus", "See you"
"Amy", "take to you later,
Thank you.
call me"

"Mark", "Try it again


Here is my code:
Expand|Select|Wrap|Line Numbers
  1. open(CSV, "test.csv") or die "Cannot open test.csv for read\n";
  2.  my $string = <CSV>;
  4.  while (<CSV>) 
  5.  {
  6.          chomp;
  7.          my @list = split (",");
  8.          foreach @list;
  9.          print "$list[0] <$list[1]>\n";
  11.  }
It read first record right, but not the second and third ones. Can someone give me some advice how to read this csv file?

Thanks a lot!!!!
May 18 '10 #1
Share this Question
Share on Google+
1 Reply

Expert 100+
P: 785
You shouldn't use "chomp" as your first command, or you will delete the needed newline-character inside your message.
Step 1.) get the next line
Step 2.) Count the number of double quotation marks inside this line
Step 3.) If there are four, you are done with the current record and can split by comma. Then chop and trim the double quotation marks on both ends. Process the resulting record data and go to step 1.
If there are less than four, you should not trim or chop or process. Instead, read the next line and concatenate it with the old. Then go to step 2.
If there are more than four, you should print out an error (too many columns) and exit the loop.

I am not sure if there could be a double quotation mark inside the message, probably escaped by a backslash or so. If so, then you need to count only the the double quotation marks without that slash in front.
May 19 '10 #2

Post your reply

Sign in to post your reply or Sign up for a free account.