By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
438,835 Members | 2,305 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 438,835 IT Pros & Developers. It's quick & easy.

newline problem when writing to a file

P: 1
Hi all,
I am new to perl and I have written a smal script to grab data from one file, and put them into another file. The problem is new lines, which are printing nice under a linux environment, but it is all messed up if I open it with notepad. I am running Perl 5 under cygwin. Heres the script:

Expand|Select|Wrap|Line Numbers
  1. #!/usr/bin/perl
  3. open (READ, "opt.txt") || die "Can't find opt.txt\n";
  5. $x=0;
  7. while ($info = <READ>) {
  8. chomp $info;
  9. @data = split (/\t/, $info);
  10. push @cells, [@data];
  11. $x++;
  12. }
  14. close READ || die "Couldn't close opt.txt";
  15. open (WRITE, ">rel.txt") || die "Can't find rel.txt\n";
  17. $y=0;
  19. print WRITE "#DoNotEditThisLine: UndoCommandFile off_files model_n_m_z endfile=/tmp/6222\n\n";
  21. foreach (@cells){
  22. print WRITE "cr balla=1,blablabla=$cells[$y][0],foobar=$cells[$y][0]_$cells[$y][1]\n";
  23. print WRITE "bleh=10175,foounbar=$cells[$y][1]\n\n";
  26. $y++;
  27. }
  29. close WRITE || die "Couldn't close rel.txt";
  30. exit (0);
Now if I cat the output in cygwin, the newlines are working. If I open it with notepad, one new line is working which is after print WRITE "bleh=10175,foounbar=$cells[$y][1]\n\n"; (please note not both of newlines are working).

Any ideas? I need those in that specific format
Feb 1 '10 #1
Share this Question
Share on Google+
1 Reply

Expert 100+
P: 785
Your problem is that different operating systems (OS) use different characters to make a line break. Therefore "\n" will be converted to one or 2 characters, depending on the OS where the program runs.

UNIX-like Linux, FreeBSD und Solaris use a single LineFeed (LF, ASCII-Code 10).
Mac OS up to Version 9 uses a sinle Carriage Return (CR, ASCII-Code 13).
MS-DOS and Windows use 2 characters to delimit a line: a CR followed by a LF.

The problem is that you have created the text under Unix-environment, therefore you have a single LF. But Notepad runs under Windows and expects CR-LF. Notepad doesn't have the feature to autodetect the correct format, but other editors do: UltraEdit, WinVi, jEdit, ... and, if you still want to stay with Microsoft:
That means: just use Wordpad instead of Notepad.
Or convert the lf to cr-lf in your text by using Cygwin command unix2dos, before opening your file in Notepad
Feb 1 '10 #2

Post your reply

Sign in to post your reply or Sign up for a free account.