Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

Re: File input-output handle defined or no determination

by Marshall (Canon)
on Nov 27, 2021 at 03:33 UTC ( #11139163=note: print w/replies, xml ) Need Help??


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.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11139163]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others surveying the Monastery: (4)
As of 2022-05-23 18:05 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Do you prefer to work remotely?



    Results (82 votes). Check out past polls.

    Notices?