newline problem when writing to a file

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Michom
    New Member
    • Feb 2010
    • 1

    newline problem when writing to a file

    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:

    [CODE=perl]
    #!/usr/bin/perl

    open (READ, "opt.txt") || die "Can't find opt.txt\n";

    $x=0;

    while ($info = <READ>) {
    chomp $info;
    @data = split (/\t/, $info);
    push @cells, [@data];
    $x++;
    }

    close READ || die "Couldn't close opt.txt";
    open (WRITE, ">rel.txt") || die "Can't find rel.txt\n";

    $y=0;

    print WRITE "#DoNotEditThis Line: UndoCommandFile off_files model_n_m_z endfile=/tmp/6222\n\n";

    foreach (@cells){
    print WRITE "cr balla=1,blablab la=$cells[$y][0],foobar=$cells[$y][0]_$cells[$y][1]\n";
    print WRITE "bleh=10175,foo unbar=$cells[$y][1]\n\n";


    $y++;
    }

    close WRITE || die "Couldn't close rel.txt";
    exit (0);
    [/CODE]

    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,foo unbar=$cells[$y][1]\n\n"; (please note not both of newlines are working).

    Any ideas? I need those in that specific format
  • chaarmann
    Recognized Expert Contributor
    • Nov 2007
    • 785

    #2
    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:
    Wordpad!
    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

    Comment

    Working...