As far as I know, you can't [Added: There is a way, see my other reply below, You *Can* Catch errors in closing lexical filehandles]. Observe,
# use Fatal qw/open print close/;
use Fatal qw/open close/;
my $result = eval {
open my $fh, '>', '/dev/full';
print $fh "Foo\n" or die $!;
};
print $result ? $result : $@, $/;
prints '1', the result of printing to the filehandle.
Placing an explicit close after the print statement gives something like,
Can't close(GLOB(0x804b548)): No space left on device at (eval 2) line
+ 3
main::__ANON__('GLOB(0x804b548)') called at -e line 1
eval {...} called at -e line 1
That uses the handy
/dev/full device of linux, for which writes always fail with
ENOSPC. The failure would have occurred on print if we had set $fh to autoflush or had printed more than a buffersworth of text.
For careful error handling, you should close your lexical handles as if they didn't know how to do it for themselves.
Update: gaal++ points out an error. Corrected.
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.