Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Output to File has additional newline characters 1

Status
Not open for further replies.

projection

Programmer
Aug 24, 2004
12
US
Hi,

Very rusty at Perl. Trying to get back into it by building simple scripts. I can't figure out what is wrong with my script. Your assistance is very much appreciated!

Trying to develop a simple script to parse a file and output to a new file.

Here is the input file contents (addresses.txt):

Name: santa claus
Email: kris.kringle@np.com
Phone: 4545454545
---------
Name: easter bunny
Email: eb@basket.com
Phone: 4545454545
---------

Here is the script:
Perl:
#!/usr/bin/perl

open (FILE, "addresses.txt");
open (FOUT, ">addr_list.txt");

while (<FILE>) {
	chomp;		
	$line = $_;  	
	
	if($line =~ m/----/) {
		print FOUT "$record\n";
		$record = "";
	} else {
		$line = substr($line, index($line," ")+1);
		$record .= ($record eq "") ? $line : "\t$line";
	}
}

close(FILE); close(OUT);

exit;


Output:
Code:
santa claus
	kris.kringle@np.com
	4545454545
easter bunny
	eb@basket.com
	4545454545
As you can see, there is a newline character after each entry. I use chomp, which is supposed to strip the newline. I tested to see if $record contained \n before and after appending. It doesn't. When I print to STDOUT, no newlines. Only when I print to a file do the newlines appear. Please save me! I have no idea what I am missing.

Thank you in advance for your help.

- Robert
 
Was addresses.txt created on the same system (or at least the same OS type) as the perl script you're running? I would guess that the line endings in your file do not match the native line endings for the OS. Take a look at the documentation for the chomp function will remove the last character from a string if it matches the value of $/ - and the $/ variable is, by default, set to the new line character for the OS you're working on.

Rather than chomp, you might be able to use:
Code:
[s]chomp;[/s]
s/[\x0a\x0d]+$//;
 
I think "chop" would do the same in this case - removing just the last charachter (whatever it is).

while (<FILE>) {
chomp;
$line = $_;
chop $line;

Long live king Moshiach !
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top