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.


In reply to Chomp is removing the whole word instead of the newline by slayedbylucifer

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • 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:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.