Given is a Perl snippet like:
{ my $fh = IO::File->new; $fh->open(">test.tmp"); print $fh "a"; }
The filehandle is closed automatically at scope exit and the file contains the expected contents.
That's quite easy in the current Perl implementation as it does reference counting. At the closing bracket the last reference to C<$fh> has gone and the file gets closed during object destruction.
As parrot isn't using reference counting for GC, we have to run a GC cycle to detect that the IO object is actually dead. This is accomplished by the "sweep 0" opcode, which does nothing if no object needs timely destruction.
If the number of objects that needs this is relatively small, we could play a trick somewhat like the following (with small changes to the perl compiler):
1. Break the filehandle object into two: a generic wrapper that uses refcounting and forwards all calls, plus the actual filehandle object.
2. All invocations on the filehandle object really get the wrapper object. If the object is passed to another method that stahses a copy, the reference count will therefore be increased.
3. At the end of the scope, explicitly check the reference count in the wrapper object. If it is one, call the destructor on the wrapper and the filehandle. If that is not one, the filehandle has 'escaped', and will no longer be subject to exact destruction.
The semantics of this are slightly different from the perl5 one, but are likely to be good enough: there is predictable destruction for objects destroyed at the end of their declaring scope.