Syntactic Confectionery Delight | |
PerlMonks |
Re: file testing is hardby dpmott (Scribe) |
on Dec 01, 2003 at 05:03 UTC ( [id://311165]=note: print w/replies, xml ) | Need Help?? |
I've had to deal with this from time to time. I also cover this in a PERL class that I teach at my company.
What I've learned, through various approaches, is that you want to depend on the result of open() (or sysopen()). A file might exist, for instance, because -e "file" returns true, but you still might not be able to open it (because, perhaps, you don't have read permissions for it, only list permissions on a UNIX system). Also, if it's important to read the file, even when you can't write to it, then you should handle reading and writing separately (as shown below). If you must be able to do both, then don't bother testing for the read-only case -- open for read+update, and fail if that doesn't work. So, when I read your problem statement, I'm left with the impression that you might be working with an INI file, which you'll create if missing, update if writable, use if read-only, and ignore if none of the above. (If that's not right, feel free to take or leave the following as you see fit). Here's how I would go about it: So, depending on what you want (i.e. load_ini or load_ini_safe), you could keep those separate or combine them or get rid of load_ini_safe. I broke them up to show a division of labor, since I was unclear about just which steps were important to you. Note that this has a small advantage over opening a file in read+update mode -- if it's read-only, then you can load it. If it's not writable, then writing fails (maybe silently in your app). If you only have write permissions for the file, you could load defaults internally and write those out (not very useful, but there it is). You get to completely avoid the error handling for trying to open a file for read+update when loading and/or saving, which would fail for both the load and the save cases if the file were read-only or write-only. Hope this helps... :)
In Section
Seekers of Perl Wisdom
|
|