Perl Conte String Truncates Beginning of a String

I am having a strange problem in perl that I cannot find the answer to.

I have a small script that will analyze data from an external sorce (be it a file, a website, etc.). After analyzing the data, it will save it in a CSV file. However, the problem is that when I write a file or print to display the data, it seems to truncate the beginning of the line. I use strict warnings and I don't see any errors.

Here is an example:

print "Name: " . $name . "\n"; print "Type: " . $type. "\n"; print "Price: " . $price . "\n"; print "Count: " . $count . "\n"; 

He will return the following:

 John Blue 7.99 5 

If I try to do it like this:

 print "$name,$type,$price,$count\n"; 

The result is the following:

 ,7.99,5 

I tried the following to find out where the problem is and get the following:

 print "$name\n"; print "$name,$type\n"; print "$name,$type,$price\n"; print "$name,$type,$price,$count\n"; 

Results:

 John John,Blue ,7.99 ,7.99,5 

I'm still learning perl, but I seem to be unable to find (possibly due to lack of knowledge) what causes this. I tried to debug the script, but in the price variable I did not see a special character that could cause this.

+4
source share
2 answers

In the @Mat sentence, I executed the output via hexdump -C and found that there was a carriage return (indicated by the hexadecimal value 0d ). Using the code $price =~ s/\r//g; to remove CR from a line of text, fixed the problem.

In addition, the input file was in Windows format, not Unix, and ran the dos2unix command to fix this.

+1
source

The line at $price ends with a carriage return. This causes your terminal to move the cursor to the beginning of the line, as a result of which the first two fields will be overwritten by the ones that follow.

You are probably reading a Windows text file in a unix window. Convert the file (for example, using dos2unix ) or use s/\s+\z//; instead of chomp; .

If CR is formed in the middle of the line, you can use s/\r//g; .

+5
source

Source: https://habr.com/ru/post/1391078/


All Articles