action #176475
Updated by tinita about 1 month ago
## Motivation
Using modern builtin perl features
https://metacpan.org/pod/Feature::Compat::Try is a module that provides the same
interface and functionality as the new `try` feature for older perl versions (<
5.34.0).
It automaticallly uses the builtin `try` feature for perl >= 5.34.0
use Feature::Compat::Try;
# In perl 5.34.0 same as:
use experimental 'try';
# Leap 16 will have perl 5.38, so as soon as we can make
# perl 5.38 the minimum version, we would write:
use v5.36; # strict, warnings, signatures, ...
use experimental 'try';
# With perl 5.40 it would be just:
use v5.40; # strict, warnings, signatures, try, ...
The basic `try/catch` feature got non-experimental with 5.40, so it's safe to
use.
The `finally` part is still experimental, so theoretically implementation
changes could happen. Would need to check the current state with Paul /
perl5porters.
## Example Feature::Compat::Try vs. eval and Try::Tiny
### Feature::Compat::Try
```
use v5.12;
use warnings;
use experimental 'signatures';
use Feature::Compat::Try;
sub foo ($fail) {
try {
say "trying";
die "oops" if $fail;
return "pass"; # returns from foo()
}
catch ($e) {
warn "Exception: $e";
return "fail"; # returns from foo()
}
finally {
say "whatever happens, I'm here";
}
say "end of subroutine"; # not reached
}
say foo(0);
say foo(1);
```
### Try::Tiny
```
use v5.12;
use warnings;
use experimental 'signatures';
use Try::Tiny;
sub foo ($fail) {
my $res;
try {
say "trying";
die "oops" if $fail;
$res = "pass";
return "pass"; # does not return from foo()
}
catch {
warn "Exception: $_";
$res = "fail";
return "fail"; # does not return from foo()
}
finally {
say "whatever happens, I'm here";
};
return $res;
}
say foo(0);
say foo(1);
```
## Pro
* In Leap >= 15.5
Compared to Try::Tiny:
* Future builtin
* Can return from subroutine
* `catch ($some_name)` instead of `$_`
* Real block syntax element`{}` - no `;` at the end needed
## Con
* Still partially experimental in 5.40