evalEmpire / perl5i

A single module to fix as much of Perl 5 as possible in one go
http://search.cpan.org/perldoc?perl5i
Other
156 stars 42 forks source link

A "boolify" operator. #301

Open schwern opened 6 years ago

schwern commented 6 years ago

Sometimes you want to return true or false, not a value which happens to be true or false. Usually this is to avoid the value being used for some undocumented purpose, or to avoid leaking private data which should not be available. Often the !! secret operator is used to "boolify" an expression.

For example...

# Accidentally returns the count of things.
sub has_things {
    return scalar @things;
}

# Returns true or false.
sub has_things {
    return !!@things;
}

Rather than use a secret operator, we could provide something like boolify to make the meaning more plain.

# Force it into scalar context so `boolify @things` works on the size of @things, not $things[0]
sub boolify($) { return !!$_[0] }

sub has_things {
    return boolify @things;
}