Hi all,
Here's a simple question I should probably already know the answer to but I
don't and the documentation thus far has not been useful. How can I tell
if a given filehandle is open?
You can't test the handle itself because if it's not open yet the compiler
complains about a bareword.
This doesn't work:
---------------------
print "Can test: ", (LOGFILE ? "true" : "FALSE" ), "\n";
I thought maybe one of the -X operators could let you ping the state of the
filehandle but if it's not open they fail with an error:
Code:
-------
my $filename = "junk.txt";
#print "Can test: ", (LOGFILE ? "true" : "FALSE" ), "\n";
print "Can read: ", (-r LOGFILE ? "true" : "FALSE" ), "\n";
print "Can write: ", (-w LOGFILE ? "true" : "FALSE" ), "\n";
open( LOGFILE, ">$filename" ) or die "Error: can't open '$filename' for
writing.\n";
#print "Can test: ", (LOGFILE ? "true" : "FALSE" ), "\n";
print "Can read: ", (-r LOGFILE ? "true" : "FALSE" ), "\n";
print "Can write: ", (-w LOGFILE ? "true" : "FALSE" ), "\n";
Result:
--------
[ ignore differences in reported line numbers ]
-r on unopened filehandle LOGFILE at perlt\testdasha.pl line 12.
Can read: FALSE
-w on unopened filehandle LOGFILE at perlt\testdasha.pl line 13.
Can write: FALSE
Can read: true
Can write: true
This suggests doing it in an eval (so the error message gets trapped) and
testing the result, but that seems like a complicated solution for a simple
problem. Can anyone suggest a better way?
Thanks very much in advance.
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>