3 ms·
Can't you just implement finally in "userspace"? In Perl, you can implement it with object destruction -- you make an instance of an object whose destructor do
by jrockway 16y ago
Can't you just implement finally in "userspace"? In Perl, you can implement it with object destruction -- you make an instance of an object whose destructor does the cleanup you want, and when it goes out of scope (exception thrown, return, etc.), the cleanup code is run.
It's extremely common to write code like:
sub work_in_tmpdir(&) {
my $cwd = cwd;
my $guard = guard { chdir $cwd };
chdir mktmp;
$_[0]->();
}
Then you can safely work in a temporary directory:
print cwd; # /home/jon
work_in_tmpdir { print cwd; die "OH NOES" }; # /tmp/3sdjkh387dh
print cwd; # /home/jon
If this doesn't look enough like Java, that's easy to fix:
sub try(&;@) {
my ($code, %args) = @_;
my $guard;
$guard = guard { $args{finally}->() }
if exists $args{finally};
my $result = eval { $code->() };
if($args{catch} && !$result){
$args{catch}->($@);
}
return $result;
}
catch(&;@) {
return catch => @_;
}
finally(&) {
return finally => $_[0];
}
(+) Now you can say:
try { something_exceptional }
catch { warn "Something bad happened: $_[0] }
finally { cleanup };
No language feature or bug tracker rant-fest required! And, I'm pretty sure that you can abuse destructors in PHP to get exactly the same result. (In Perl, that "guard" function from the Guard module is implemented something like: class Foo { has 'cleanup' => (is => 'ro', isa => CodeRef ); sub DESTROY { $self->cleanup->() } }; sub guard(&){ return Foo->new( cleanup => $_[0] ) })
(+) Also, don't cut-n-paste this code into your apps. It misses special cases. use Try::Tiny, TryCatch, etc. from the CPAN.
- bad_user 16y agoThat's a neat example, but you're abusing Perl's syntax for that syntactic-sugar, and it doesn't work like that in PHP (e.g. parens cannot be omitted, and does this code even compile with "use strict"?)
- jrockway 16y agoIt compiles with "use strict", and it's not abuse. The reason you can't compile it is because guard is not defined, nor are cwd, cleanup, and the other placeholder functions I used. When you are relying on the parser to add parens for you (and let you omit "sub"), you have to have the function in scope. Compare: use strict; sub foo { bar } And use strict; sub bar; sub foo { bar };
- bad_user 16y ago"abuse" was not the word I was looking for: I meant you're using Perl's syntactic freedom, and this trick does not work with PHP.
- jerf 16y agoIf you think that's "abusing" Perl 5 syntax for a useful effect, you should start reading up on Perl 6. Though you probably shouldn't if you have a weak heart.
- chromatic 16y ago[You're] abusing Perl's syntax for that syntactic-sugar... Those are designed, documented, and tested features; they exist to do exactly this.