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

Re: Catching errors in closing lexical filehandles

by Zaxo (Archbishop)
on Sep 27, 2004 at 05:43 UTC ( #394074=note: print w/ replies, xml ) Need Help??


in reply to Catching errors in closing lexical filehandles

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.

After Compline,
Zaxo


Comment on Re: Catching errors in closing lexical filehandles
Select or Download Code
Re^2: Catching errors in closing lexical filehandles
by gaal (Parson) on Sep 27, 2004 at 05:53 UTC
    Hey, I didn't know about Fatal, cool. Unfortunately it seems broken on my system:
    Cannot make a non-overridable builtin fatal at /usr/share/perl/5.8/Fat +al.pm line 108. BEGIN failed--compilation aborted at f.pl line 1.
    I wonder, does this do anything different?
    use Fatal qw/open close/; my $result = do { open my $fh, '>', '/dev/full'; print $fh "Foo\n"; }; print $result ? $result : $@, $/;
    Also it's probably worth trying to put in an extra nonces value at the end of the block, like "37", just to disambiguate the value of print from some mysterious other factor.

      Arrgh! I keep falling afoul of print not being overridable! Leave it off the import list. I'll correct the code above.

      After Compline,
      Zaxo

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (9)
As of 2014-12-19 00:45 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (69 votes), past polls