Let's say I have a resource (for example, a file descriptor or a network socket) that needs to be freed:
open my $fh, "<", "filename" or die "Couldn't open filename: $!"; process($fh); close $fh or die "Couldn't close filename: $!";
Suppose process can die. Then the code block exits early and $fh does not close.
I can explicitly check for errors:
open my $fh, "<", "filename" or die "Couldn't open filename: $!"; eval {process($fh)}; my $saved_error = $@ ; close $fh or die "Couldn't close filename: $!"; die $saved_error if $saved_error;
but this type of code, as you know, is difficult to get correctly, and only gets more complicated when adding additional resources.
In C ++, I used RAII to create an object that owns the resource and whose destructor frees it. This way, I donβt have to forget to free the resource, and the cleaning of the resources happens correctly as soon as the RAII object goes out of scope - even if an exception is thrown. Unfortunately, in Perl, the a DESTROY method is unsuitable for this purpose, since there is no guarantee when it will be called.
Is there a Perlish method that automatically releases resources, even with exceptions? Or an obvious error checking the only option?
source share