Perl Idioms Explained - !!expr
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 littlesub 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
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.use Data::Dumper; my $val = 'a string which evaluates to true'; print Dumper !$val; print Dumper !!$val; __output__ $VAR1 = ''; $VAR1 = '1';
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.
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: Perl Idioms Explained - !!expr
by Anonymous Monk on Jul 14, 2004 at 13:09 UTC | |
by broquaint (Abbot) on Jul 14, 2004 at 13:17 UTC | |
by japhy (Canon) on Jul 14, 2004 at 14:46 UTC | |
by davidrw (Prior) on Nov 05, 2005 at 02:55 UTC | |
Re: Perl Idioms Explained - !!expr
by ihb (Deacon) on Jul 20, 2004 at 01:20 UTC |
Back to
Tutorials