http://www.perlmonks.org?node_id=983589

slayedbylucifer has asked for the wisdom of the Perl Monks concerning the following question:

Hi,

I am facing issues with perl chomp function. I have a test.csv as below:

col1,col2 vm1,fd1 vm2,fd2 vm3,fd3 vm4,fd4

I want to print the 2nd field of this csv. This is my code:

#!/usr/bin/perl -w use strict; my $file = "test.csv"; open (my $FH, '<', $file); my @array = (<$FH>); close $FH; foreach (@array) { my @row = split (/,/,$_); my $var = chomp ($row[1]); ### <<< this is the problem print $var; }

The output of aboe code is :

11111

I really don't know what is "11111". Actually, the last field can be printed as below:

foreach (@array) { my @row = split (/,/,$_); print $row[1]; ### << Note that I am not printing "\n" }

the output is:

vm_cluster fd1 fd2 fd3 fd4

Now, i am using these field values as an input to the DB and the DB INSERT statement is failing due this invisible newline. So I thought chomp would help me here. instead of chomping, it gives me "11111".

I also tried below loop:

foreach (@array) { my @row = split (/,/,$_); chomp ($row[1]); my $var = $row[1]; print $var; }

But above loop will not print anything (not even the "11111" output mentioned above). Meaning, chomp is removing the last string and the trailing new line.

Could you help me understand what am i doing wrong here.

Also please find my discussion on stackoverflow for this issue: http://stackoverflow.com/questions/11645696/perls-chomp-chomp-is-removing-the-whole-word-instead-of-the-newline

Thanks.