PrePAN

Sign in to PrePAN

Util::one small function to make sure there is only one result

Author
torbjorn@github
Date
URL
Status
In Review
Good

Synopsis

use Util::one;

my @one_element = one grep /foobar/, qw(foobar foo baz test); # \@one_element is ['foobar']
my $one_element = one grep /foobar/, qw(foobar foo baz test); # $one_element is 'foobar'

my @gives_error = one grep /foo/, qw(foobar foo baz test); # ERROR: more than one values returned

my @also_error = one grep /no_match/, qw(foobar foo baz test); # ERROR: no values returned


Description

The module provides the function 'one' which assures there is only one element returned in list context from the preceding expression.

I repeat this pattern again and again, checking if the outcome provides only the one thing I search for, where finding none or two or more will be an error, repeating the same checks and the same error messagse over and over. 'one' solves that.

Comments

I don't know if Util:: is the right namespace for this, probably is
Util is most certainly the wrong namespace.
Util is the wrong TLNS, but which is the right one? Also, ::one is wrong; it should at least be ::One, but “one” is a bit nondescript too. Maybe List::Util::Single?

Maybe call the function `exactly_one` (along with `at_most_one`, which is something I’ve checked for in code of my own)?

Please sign up to post a review.