DEV Community

Cover image for Released Result::Simple - a dead simple perl-ish Result like F#, Rust, Go
kobaken
kobaken

Posted on

2

Released Result::Simple - a dead simple perl-ish Result like F#, Rust, Go

https://metacpan.org/pod/Result::Simple

Result::Simple is a dead simple Perl-ish Result.

Result represents a function's return value as success or failure, enabling safer error handling and more effective control flow management. This pattern is used in other languages such as F#, Rust, and Go.

In Perl, this pattern is also useful, and this module provides a simple way to use it. This module does not wrap a return value in an object. Just return a tuple like ($data, undef) or (undef, $err). For example, take a look at a implement of Ok function:

# When the function is successful, it should return this.
sub Ok {
    if (CHECK_ENABLED) {
        croak "`Ok` must be called in list context" unless wantarray;
        croak "`Ok` does not allow multiple arguments" if @_ > 1;
        croak "`Ok` does not allow no arguments" if @_ == 0;
    }
    ($_[0], undef)
}
Enter fullscreen mode Exit fullscreen mode

It is a dead simple!

However, it decreases the bugs. For instance, if you forget to handle $err, it can be detected by Perl::Critic::Policy::Variables::ProhibitUnusedVarsStricter. This is one of effectiveness of Result pattern!

Image description

Feel free to give it a try!

——-

This blog is for Japanese perl advent calendar 2024.

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay