Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW

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.

Replies are listed 'Best First'.
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.



    "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?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://506436]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others lurking in the Monastery: (4)
As of 2018-06-22 06:09 GMT
Find Nodes?
    Voting Booth?
    Should cpanminus be part of the standard Perl release?

    Results (121 votes). Check out past polls.