A
Andrei Alexandrescu (See Website For Email)
Hello,
I set out to write a useful OnScopeExit feature that's supposed to
execute some code when the current scope is exited. What I came up with is:
package OnScopeExit;
my $todo = sub {};
sub new { shift; $todo = shift; bless {}; }
sub DESTROY {
&$todo;
}
package main;
sub OnScopeExit(&) {
return new OnExit(shift);
}
Now I can say in any scope I please:
{
... code ...
my $tempFile = "/tmp/temp.txt";
my $cookie1 = OnScopeExit { unlink($tempFile); };
... code ...
}
Sure enough, when the current scope exits, the local $cookie1 will have
its reference count go to zero, the DESTROY sub gets called, and the
code that deletes the temporary file is invoked. Very nice.
The only annoying part is that I need to define some "my" variable with
a unique name for each OnScopeExit action I want to perform. Ideally,
I'd only need to write:
{
... code ...
my $tempFile = "/tmp/temp.txt";
OnScopeExit { unlink($tempFile); }
... code ...
}
that is, the creation of a lexically-scoped anonymous variable that will
go out of scope should be somehow automated.
I looked through symbol tables, scratchpads, and the ilk, for a couple
of hours, to no avail. Is there a way?
Thanks,
Andrei
I set out to write a useful OnScopeExit feature that's supposed to
execute some code when the current scope is exited. What I came up with is:
package OnScopeExit;
my $todo = sub {};
sub new { shift; $todo = shift; bless {}; }
sub DESTROY {
&$todo;
}
package main;
sub OnScopeExit(&) {
return new OnExit(shift);
}
Now I can say in any scope I please:
{
... code ...
my $tempFile = "/tmp/temp.txt";
my $cookie1 = OnScopeExit { unlink($tempFile); };
... code ...
}
Sure enough, when the current scope exits, the local $cookie1 will have
its reference count go to zero, the DESTROY sub gets called, and the
code that deletes the temporary file is invoked. Very nice.
The only annoying part is that I need to define some "my" variable with
a unique name for each OnScopeExit action I want to perform. Ideally,
I'd only need to write:
{
... code ...
my $tempFile = "/tmp/temp.txt";
OnScopeExit { unlink($tempFile); }
... code ...
}
that is, the creation of a lexically-scoped anonymous variable that will
go out of scope should be somehow automated.
I looked through symbol tables, scratchpads, and the ilk, for a couple
of hours, to no avail. Is there a way?
Thanks,
Andrei