http://www.perlmonks.org?node_id=1134400

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

Hello again Monks!

Another day - another mystery. This time is about double bitwise negation (or strange form of smartmatch)

First encountered in DBM::Deep:

my %is_legal_filter = map { $_ => ~~1 } qw( store_key store_value fetch_key fetch_value );

Than, in Devel::Declare (even stranger form):

set_in_declare(~~@{$temp_name||[]});

Deparse says that at least first one is double negation, no-op. So - what for?

P.S. is the second example just a weird replacement for scalar ?

Replies are listed 'Best First'.
Re: The mystery of double bitwise negation
by BrowserUk (Patriarch) on Jul 12, 2015 at 18:04 UTC

    I'd say that the first one was completely pointless. Double bit-wise inversion of the constant 1 serves no purpose at all:

    C:\test>perl -MDevel::Peek -le" my($m,$n) = (1,~~1); print Dump($m), ' + ', Dump( $n )" SV = IV(0x2ca374) at 0x15501c REFCNT = 1 FLAGS = (PADBUSY,PADMY,IOK,pIOK) IV = 1 SV = IV(0x2ca378) at 0x155010 REFCNT = 1 FLAGS = (PADBUSY,PADMY,IOK,pIOK) IV = 1

    The second is a golfed version of scalar. Why? No idea.


    With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.
    I'm with torvalds on this Agile (and TDD) debunked I told'em LLVM was the way to go. But did they listen!
Re: The mystery of double negation
by shmem (Chancellor) on Jul 12, 2015 at 17:20 UTC

      Nope, it's bitwise negation and doesn't work this way. It's basically - noop. Keeps value the same.

        The point of Double Negation is casting [...] any false value to 0.
        Nope, it's bitwise negation and doesn't work this way. It's basically - noop. Keeps value the same.

        Um:

        % say "(!1)" % say "~~(!1)" 0

        So it could be an idiom that is applied to all Boolean values (so that Boolean false shows up as '0' instead of as the "invisible" ''). It just does nothing when the Boolean value is already 1.

        - tye        

        Right you are. Then... maybe chromatic can enlighten us?

        perl -le'print map{pack c,($-++?1:13)+ord}split//,ESEL'
        You're right, but, still, ~~1 will return 1, i.e a true value. Why the author of the module did that, I have no idea.
Re: The mystery of double bitwise negation
by ikegami (Patriarch) on Jul 13, 2015 at 17:04 UTC
    For integers, it's no-op that evaluates its operand in scalar context. So,
    set_in_declare(~~@{$temp_name||[]});
    is being used in place of
    set_in_declare(scalar(@{$temp_name||[]}));