Perl Idioms Explained - !!expr
sub is_in_list {
return !!grep { $_ eq $_[0] } @_[ 1 .. $#_ ];
}
print "baz is in list"
if is_in_list 'baz', qw/ foo bar baz /;
__output__
baz is in list
Even though perl doesn't have a native boolean type, sometimes all a
programmer wants is a nice simple boolean value, and this is what the
!!expr idiom provides. Given an expression, its resulting
value is negated by the boolean not operator
! and then
that value is negated to get the resulting boolean value. Let's
break that down a little
use Data::Dumper;
my $val = 'a string which evaluates to true';
print Dumper !$val;
print Dumper !!$val;
__output__
$VAR1 = '';
$VAR1 = '1';
So as we can see there the initial negation returns a false value
(an empty string
'') to signify the negated truthfulness
of the value. Then secondary double negation returns a true value
(the integer
1) as the negated form of the false value.
Caveats
Because it is producing a boolean value from an expression it will
not preserve any additional information from the expression. But that's
about the only caveat, if you could consider it one, and it has the
added plus of acting as a boolean internally as explored in
diotalevi's Re: Converting to boolean.
Summary
Because we are lacking a ¡ operator the !!expr
idiom serves to derive a boolean value from an arbitrary expression.