in reply to file creating AND writing error
if (!-e "$log"){ open(CREATE, "+>>$log") or die "$log failed: $!\n"; while (<CREATE>){ foreach $ser(@ser) { printf "%3s",$ser; } print "\n"; } close(CREATE); }
You have various problems with your code. Some fundamental, some just problemetic.
First, you're checking to see if the file doesn't exist, then you open it. This is a race condition; the file could appear between when you check it and when you open it. You should always rely on the open to tell you if a file doesn't exist, and you should always use a mode that requires this. You should also always check your open; just because the file exists doesn't mean the open won't fail. The simplest way to accomplish what you're doing is to use sysopen; it will allow you to create the file, but if it already exists it will fail. For example:
use Fcntl qw(O_CREAT O_EXCL O_APPEND O_RDWR); if (sysopen(CREATE, $log, O_APPEND|O_RDWR|O_EXCL|O_CREAT)) { ... CREATE is now open, do something with it ... } else { warn("Unable to open log file '$log': $!.\n"); }
That code will open the file for read, write, and append, and create the file. If the file could be opened then it handles CREATE; if not it warns and does nothing.
Now, once you've resolved that, you will have another problem; as mentioned by dave_the_m, you are attempting to read from a file almost guaranteed to be empty. I'm not sure what you were trying to accomplish here; if you just want to print the contents of @ser to the file:
... open CREATE ... foreach my $ser (@ser) { printf CREATE "%3s", $ser; }
Now, if you got the logic wrong, and want to open the log file if it does exist, you should be aware that mixing reads and appends to the same file, without seeking in between, won't work (though it may on some systems); each time you write the seek pointer will be reset to the end of the file.
Hopefully that clears up some confusion. If you are still having problems you should write back with a description of what you want to do, as your code doesn't make it clear.
|
|---|