Perl: adding a string to $ _ produces strange results

I wrote a super simple script:

#!/usr/bin/perl -w use strict; open (F, "<ids.txt") || die "fail: $!\n"; my @ids = <F>; foreach my $string (@ids) { chomp($string); print "$string\n"; } close F; 

This produces the expected output of the entire contents of the ids.txt file:

Hi

world

this is

annoying

Source

the lines

Now I want to add a file extension: .txt for each line. This line should do the trick:

  #!/usr/bin/perl -w use strict; open (F, "<ids.txt") || die "fail: $!\n"; my @ids = <F>; foreach my $string (@ids) { chomp($string); $string .= ".txt"; print "$string\n"; } close F; 

But the result is as follows:

.txto

.txtd

.txte

.txtying

.txtcecode

Instead of adding ".txt" to my lines, the first 4 letters of my line will be replaced by ".txt". Since I want to check if any files exist, I need the full file name with the extension.

I tried chopping, chomp, replacing (s / \ n //), merging and whatever. But the result remains a replacement instead of adding.

Where is the mistake?

+7
source share
3 answers

Chomp does not remove BOTH \r and \n if the file has a DOS line ending and you are running Linux / Unix.

What you see is actually the original line, a carriage return, and an extension that overwrites the first 4 characters on the display.

If the input file has DOS / Windows line endings, you should delete both:

 s/\R+$// 
+15
source

A useful debugging technique when you are not quite sure why your data is set up for what it is is to dump data using Data :: Dumper:

 #!/usr/bin/perl -w use strict; use Data::Dumper (); $Data::Dumper::Useqq = 1; # important to be able to actually see differences in whitespace, etc open (F, "<ids.txt") || die "fail: $!\n"; my @ids = <F>; foreach my $string (@ids) { chomp($string); print "$string\n"; print Data::Dumper::Dumper( { 'string' => $string } ); } close F; 
+1
source

Have you tried this?

 foreach my $string (@ids) { chomp($string); print $string.".txt\n"; } 

I'm not sure what happened to your code. these results are strange

0
source

All Articles