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 where the “1” is comming from. Actually, the last filed 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”.
Could you help me understand what am i doing wrong here.
Thanks.
Adding more information after reading loldop’s responce:
If I write as below, then it will not print anything (not even the “11111” output mentioned above)
foreach (@array)
{
my @row = split (/,/,$_);
chomp ($row[1]);
my $var = $row[1];
print $var;
}
Meaning, chomp is removing the last string and the trailing new line.
The reason you see only a string of
1s is that you are printing the value of$valwhich is the value returned fromchomp.chompdoesn’t return the trimmed string, it modifies its parameter in-place and returns the number of characters removed from the end. Since it always removes exactly one"\n"character you get a1output for each element of the array.You really should
use warningsinstead of the-wcommand-line option, and there is no reason here to read the entire file into an array. But well done on using a lexical filehandle with the three-parameter form ofopen.Here is a quick refactoring of your program that will do what you want.