Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??
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.


In reply to Perl Idioms Explained - !!expr by broquaint

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others studying the Monastery: (4)
As of 2024-04-24 01:17 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found