View Full Version : strange output
windowcleaner
11-19-2005, 11:16 AM
I've got the following code in my script which adds a name and a idnumber (with a space in front of it) to a textfile.
open COLOURS, ">>myfile.txt" or die "ALWAYS INCLUDE ERROR CHECKS";
flock(COLOURS, LOCK_EX);
print COLOURS $namE."\n";
print COLOURS " ".$idnumber."\n";
close COLOURS;
For some reason the name of the second contribution is placed directly behind the idnumber of the first contribution. What am I doing wrong here ?
sample output:
Mark
v9hp2w9gDarwin
6arjkj4g
mlseim
11-19-2005, 05:06 PM
I tried your snippet and this is how "myfile.txt" looks:
Bill Smith
1234567
Mark Johnson
5673432
It works just like you want it to, with the space you inserted before the id number.
So, I'm thinking you have a problem with the script that pulls out the data and displays it. Maybe you can show us the script you have for reading the data.
When you read the data, I'm guessing you do a "chomp" or "chop".
That's where your problem might be. "chomp" removes any carriage returns from the data it reads, and "chop" removes the last character. So, you're removing your newline "\n" each time you read your name and id.
It's fine to use "chomp", but you just need to remember to add it back in after you read it from the "myfile.txt".
FishMonger
11-19-2005, 05:18 PM
Suggestions:
Include the system's error message in the die statement.
Use seek to make sure you're at the end of the file. It's possible that another process is writting to the file inbetween the time it takes to open the file and achieve the lock.
Use 1 print statement, not 2.
Put the name and ID number on the same line, seperated by a colon; this will make it easier when you need to parse the file.
Unlock the file before closing it.
open COLOURS, ">>myfile.txt" or die "ALWAYS INCLUDE ERROR CHECKS $!";
flock(COLOURS, LOCK_EX);
seek(COLOURS, 0, 2);
print COLOURS "$namE:$idnumber\n";
flock(COLOURS, LOCK_UN);
close COLOURS;
If you want to put the name and Id on seperate lines then I'd still use 1 print statement:
print COLOURS "$namE\n$idnumber\n";
windowcleaner
11-20-2005, 09:29 AM
Thank you both.. I didnt chop the values before writing to the text file..so thats why the bug occured. And thank you Fishmonger for pointing me out some things.... although I allways thought that the flock was automaticly unlocked when the text file was closed ?
FishMonger
11-20-2005, 05:47 PM
I allways thought that the flock was automaticly unlocked when the text file was closed ?
That’s true, but it’s use is preferred for completeness and so that there’s no ambiguity.
vBulletin® v3.8.2, Copyright ©2000-2012, Jelsoft Enterprises Ltd.