http://qs1969.pair.com?node_id=11139163


in reply to File input-output handle defined or no determination

Your code,  open R,"$file" will by default open global symbol R for reading.

Better is:
open my $R, '<', "$file" or die "your specific message $!";
Use a lexical variable, "my" instead of a package global, explicitly say this is for reading (or writing), print an error message and exit your program (i.e. die) if the open does not succeed.

For a disk file, you can assume that all subsequent "prints" to that filehandle will work. There is no need to check if the file handle is still open, it is.

There are boundary cases where the write to a file will fail (like filesystem full) and there are situations where a connection to a network file socket will be lost. Handling those cases are beyond what you are asking about.

Update: While jwkrahn's answer is factually correct, this doesn't have much meaning in practical Perl code. When you open a file handle, you should check that the open worked, and if it did, thereafter you should assume that the file handle is still open. At low level C code, there is such a thing as a fileno. But you will very likely will never ever encounter or need this number in Perl. Just because a file handle is "open", that does not mean that actually using it to read or write will work. At the end of the day, "the proof is in the pudding" - you have to actually use the filehandle in order to know if it indeed works to get or send data.

Replies are listed 'Best First'.
A reply falls below the community's threshold of quality. You may see it by logging in.