David Mordigal
David Mordigal

Reputation: 409

Perl automatically adds newline to output file

I am using Perl to write to a file. It keeps adding a newline to the output file in the same spot even after I use chomp. I cannot figure out why.

Sample Code (reading from an input file, processing the line and then writing that line out to the output file):

open(OUT, "> out.txt");
# ...
while(<STDIN>) {
    # ...
    my $var = substr($_, index($_, "as "));
    chomp($var);
    print("Var is: " . $var); # no newline
    print OUT $var . ","; # adds newline before the comma
    # ...
}
# ...
close(OUT);

Any ideas as to what might be causing this or how to fix it? Thanks.

Upvotes: 0

Views: 1014

Answers (1)

Juan Diego Godoy Robles
Juan Diego Godoy Robles

Reputation: 14955

The cannonical procedure:

while(<STDIN>) {
    chomp;
    # ...
    my $var = substr($_, index($_, "as "));
    print("Var is: " . $var); # no newline
    print OUT $var . ","; # adds newline before the comma
    # ...
}

In most operating systems, lines in files are terminated by newlines. Just what is used as a newline may vary from OS to OS. Unix traditionally uses \012 , one type of DOSish I/O uses \015\012 , Mac OS uses \015 , and z/OS uses \025 .

Perl uses \n to represent the "logical" newline, where what is logical may depend on the platform in use. In MacPerl, \n always means \015 . On EBCDIC platforms, \n could be \025 or \045 . In DOSish perls, \n usually means \012 , but when accessing a file in "text" mode, perl uses the :crlf layer that translates it to (or from) \015\012 , depending on whether you're reading or writing. Unix does the same thing on ttys in canonical mode. \015\012 is commonly referred to as CRLF.

To trim trailing newlines from text lines use chomp(). With default settings that function looks for a trailing \n character and thus trims in a portable way.

In this case you're hitting a cross-platform barrier, you're reading documents written on an os, from a different and not compatible platform.

For an isolated execution you should covert your file line endings to match the host.

To address the issue permanently, you can try: https://metacpan.org/pod/File::Edit::Portable . Thanks @stevieb

Upvotes: 3

Related Questions