[Za-pm] creating new file one line at a time

James E Keenan jkeen at verizon.net
Sun Mar 7 16:17:04 PST 2010


(I didn't realize that my first post only went to Anne.  So, for the  
benefit of the list ...)


In Perl, when you read a record like this, you are reading it newline  
and all.  So what we almost always do is to first clear off the  
newline.  Then we analyze/rewrite the line as needed.  Then we print  
it to the write handle with a newline.

Try:

while (<IMPORT>) {
   chomp;
   print RESULT "$_|\n";
}

Note:  You are using global filehandles here.  Lexically scoped  
filehandles have been available in Perl since (I think) the  
introduction of 5.8 in 2002.  They're considered "best practice."  So  
what you really want in your 'open' statements is:

open my $IMPORT, '<', "import.txt" ...
open my $RESULT, '>', "delimited.txt"

... which also illustrates the 3-argument form of 'open', which is  
often (though perhaps not universally) also considered best practice.


And now to follow up further ...


I know that at my $dayjob we often have input of character-delimited  
records that arrives in DOS format.  What that means is that the  
lines actually end in '\r\n'.  One of the other programmers wrote a  
function called 'chew()' that essentially does this:

$line =~ s/(.*)(\r\n)*/$1/;

In your case, chomp may not be eliminating a final \r, so when you  
append a pipe it appears on the next line.



More information about the Za-pm mailing list