Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
PerlMonks  

Re: How do I tell if a handle is open for writing?

by sgifford (Prior)
on Nov 07, 2005 at 17:00 UTC ( #506436=note: print w/ replies, xml ) Need Help??


in reply to How do I tell if a handle is open for writing?

Try writing nothing at all to the file, and see if it fails:

sub is_writable_fh { my($fh)=@_; local $\=''; return print $fh ''; } open(F1,"< $0") or die "Couldn't open '$0' for read: $!\n"; print "F1 is".(is_writable_fh(\*F1)?"":"n't")." writable.\n"; open(F2,">> $0") or die "Couldn't open '$0' for append: $!\n"; print "F2 is".(is_writable_fh(\*F2)?"":"n't")." writable.\n";

Zaxo's solution will tell you whether you have write permissions to the file, but not whether you have write permissions to the filehandle.


Comment on Re: How do I tell if a handle is open for writing?
Download Code
Re^2: How do I tell if a handle is open for writing?
by DrWhy (Chaplain) on Nov 07, 2005 at 17:44 UTC
    Excellent! I had thought about just trying to write something to the file but didn't want to modify the file. It didn't occur to me to write *nothing* to the file :)

    I was worried that even this solution might have unintended side effects, e.g., changing the modified time on the file or (less likely in my mind) writing a null character to the file. I tried it on my WinXP system and it doesn't appear to modify the file in any way -- modified date remains unchanged.

    Thanks!

    --DrWhy

    "If God had meant for us to think for ourselves he would have given us brains. Oh, wait..."

      It should write an EOF at the position (on Win that is, or was it FAT-filesystem only?) and everything after it would be lost. Of course perl could intervene and take it to mean a check for writability, and then use other means to check and get you the result. But I would first seek to EOF.

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others surveying the Monastery: (7)
As of 2014-09-02 10:04 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My favorite cookbook is:










    Results (21 votes), past polls