jmusbach has asked for the wisdom of the Perl Monks concerning the following question:

Hello, I'm working on a DNS decoder and as part of it I need to manipulate bitmasks. I referred to a online source for the bitmasks since that is my weak point and discovered something funky that I don't quite understand. If I use bitmask manipulation like so:
#split apart flags my $qr=$flags & 0x8000; my $opcode=($flags & 0x001e) >> 11; my $aa=$flags & 0x0400); my $tc=$flags & 0x0200; my $rd=$flags & 0x0100; my $ra=$flags & 0x0080; my $rcode=$flags & 0x000f;
The result is wrong:
ID: 2 QR: 1 OPCODE: 0 AA: 0 TC: 0 RD: 256 RA: 128 RCODE 0 QDCOUNT: 1 ANCOUNT: 6 NSCOUNT: 0 ARCOUNT: 0
(note RD and RA)... Yet if I change the bitmasks like so:
#split apart flags my $qr=! ! ($flags & 0x8000); my $opcode=($flags & 0x001e) >> 11; my $aa=! ! ($flags & 0x0400); my $tc=! ! ($flags & 0x0200); my $rd=! ! ($flags & 0x0100); my $ra=! ! ($flags & 0x0080); my $rcode=$flags & 0x000f;
to include "! !" the results are valid:
ID: 2 QR: 1 OPCODE: 0 AA: TC: RD: 1 RA: 1 RCODE 0 QDCOUNT: 1 ANCOUNT: 6 NSCOUNT: 0 ARCOUNT: 0
Why? What does "! !" do?

Replies are listed 'Best First'.
Re: What does "! !" do?
by tobyink (Canon) on Feb 06, 2012 at 14:23 UTC

    It's effectively a "cast to boolean" operation.

    Consider you have a variable $x which might contain a string, or might contain a number - you're not quite sure. If you want to force it to be treated as a string, you do something like this:

    say ($x . ""); # concatenate an empty string to it

    Or if you want to force it to be treated as a number:

    say ($x + 0); # add zero to it

    !! does the same for forcing things to be a "boolean". Perl doesn't have real booleans (though there are CPAN modules for that) so in this case uses the empty string to represent false, and the number 1 to represent true.

    How does it work? A single ! is just a "not" operation. Two not operations cancel each other out truth-wise, but still act to cast the value to boolean.

Re: What does "! !" do?
by SuicideJunkie (Vicar) on Feb 06, 2012 at 14:18 UTC

    See: Perlop

    You're looking at a pair of negation operators. By doubling it up, you keep the true values true and the false values false, but convert all true values down to a 1.

    More concisely written as !!(expression), you can think of it as a boolean-ization operator

Re: What does "! !" do?
by Anonymous Monk on Feb 06, 2012 at 14:16 UTC