Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
PerlMonks  

Re: Printing a String (TOO stupid?)

by Laurent_R (Parson)
on Jun 18, 2014 at 18:51 UTC ( #1090331=note: print w/ replies, xml ) Need Help??


in reply to Printing a String (TOO stupid?)

This is obviously a problem with Windows files used under Unix (I have been through that several times, I know now where it comes from, but the first time it took me a while to figure out). Under Unix, the chomp function removes only the "\n" part of the line end, and the "\r" also present in Windows line ends stay there and put the subsequent characters to the start of the line (overwriting whatever is there). Use this:

chomp $line; $line =~ s/\r//g;
or
$line =~ s/[\r\n]//g;
Update: Corrected two typos (a silly colon before the g regex modifier and a missing /) in the second regex. Thanks to poj for having pointed out them to me.


Comment on Re: Printing a String (TOO stupid?)
Select or Download Code
Re^2: Printing a String (TOO stupid?)
by AnomalousMonk (Monsignor) on Jun 19, 2014 at 09:43 UTC
    ... a problem with Windows files used under Unix ...

    If this is certain to be the situation, I think I would take the approach of local-ly changing  $/ (see perlvar) to  "\x0d\x0a" to control both the reading of Windoze-ish lines from a filehandle and the behavior of chomp in removing their line-enders. Something like:

    open my $fh ... or die ...; ... { local $/ = "\x0d\x0a"; while (defined(my $line = <$fh>)) { chomp $line; do_something_with($line); } }
    Both problems handled in one swell foop. (Of course, you have to be aware that the change to the global  $/ propagates 'into' the  do_something_with() call and into anything that function may call, but that's a post for another day.)

      Yes, that's another interesting way to do it. As for whether it is certain that it is a problem with Windows files used under Unix, I of course cannot be sure without having seen the file itself, but I know for a fact that I have met that problem a few times and got exactly the same symptoms: the words added to the end of the lines were coming over the start of the lines. And it took me at least an hour to figure out what the issue was the first time I got it.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1090331]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others meditating upon the Monastery: (12)
As of 2014-08-28 15:28 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The best computer themed movie is:











    Results (263 votes), past polls