Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unexpected result of string concatenation

Tags:

perl

I have written following code to read from a file list of filenames on each line and append some data to it.

open my $info,'<',"abc.txt";
while(<$info>){

    chomp $_;
    my $filename = "temp/".$_.".xml";

    print"\n";
    print $filename;
    print "\n";

}

close $info;

Content of abc.txt

file1
file2
file3

Now I was expecting my code to give me following output

temp/file1.xml
temp/file2.xml
temp/file3.xml

but instead I am getting output

.xml/file1
.xml/file2
.xml/file3
like image 946
Prabhat Avatar asked Aug 19 '14 13:08

Prabhat


1 Answers

Your file has windows line endings \r\n. chomp removes the \n (Newline) but leaves the \r (Carriage return). Using Data::Dumper with Useqq you can examine the variable:

use Data::Dumper;
$Data::Dumper::Useqq = 1;
print Dumper($filename);

This should output something like:

$VAR1 = "temp/file1\r.xml";

When printed normally, it will output temp/file, move the cursor to the start of the line and overwrite temp with .xml.

To remove the line endings, replace chomp with:

s/\r\n$//;

or as noted by @Borodin:

s/\s+\z//;

which "has the advantage of working for any line terminator, as well as removing trailing whitespace, which is commonly unwanted"

like image 67
RobEarl Avatar answered Nov 14 '22 22:11

RobEarl