in reply to How does ~~ force string interpolation of code into scalar context?

So sometime human being confuse themselves. As sauoq pointed out, ~~ is nothing more than ~ and ~ again.

However I disagree with one point bart mentioned in his post, in which he said that ~ works differently agasinst integer and string. In fact, it works in exactly the same way against integer and string. This becomes crystal clear if you understand this at the bit level (0=>1, 1=>0), not the human interpretation of those bits:

use strict; use warnings; #integer 32 bit { my $a = 1; print "a = $a\n"; #a: 00000001, ~ - fffffffe print 0xfffffffe, "\n"; print "~a = ", ~$a, "\n"; } #string { my $a = "abcd"; (my $a_ord = $a) =~ s/(.)/sprintf "%02x", ord $1/ge; print "a = $a\n"; print "a_ord = $a_ord\n"; #a: 97, hex - 61, ~ - 9e #b: 98, hex - 62, ~ - 9d #c: 99, hex - 63, ~ - 9c #d: 100, hex - 64, ~ - 9b my $b = ~$a; (my $b_ord = $b) =~ s/(.)/sprintf "%02x", ord $1/ge; print "b_ord = $b_ord\n"; }
  • Comment on Re: How does ~~ force string interpolation of code into scalar context?
  • Download Code

Replies are listed 'Best First'.
Re: Re: How does ~~ force string interpolation of code into scalar context?
by bart (Canon) on Oct 25, 2003 at 23:31 UTC
    In fact, it works in exactly the same way against integer and string.
    Does not. Try this:
    $\ = "\n"; print ~3; print ~"3";
    Result:
    4294967292
    Ì
    
    Now, if it worked exactly the same way for integers and for strings, how come the intermediate result is different?

    I stand by my point: even though they work differently (as shown here), the net result of the double not is exactly the same for both: the original value. That means that an integer produces the original integer, and that a string produces the original string.

    Perhaps you mean something other than I do?

      Perhaps you mean something other than I do?

      If I had to guess — and I do — I think he does mean something different than you do. I understand the points both of you are trying to make.

      Your two examples "work differently" only because you are, in reality, providing different data and interpretting the answer differently. It'll come as no surprise to you that they work the same if you make other things equal...

      print ~"3"; print pack("c",~ord("3")); # Or... print ~3 print unpack("L", ~"\x00\x00\x00\x03");
      and I think that's pg's point.

      Your point, however, is really that Perl does treat strings and integers differently. And it's a good point. Another example that clears things up a bit:

      $x = "3"; print ~$x; # This is... $x = 3; print ~$x; # Not the same as this... $x .= ""; print ~$x; # But, after stringification, it is.
      So, you're both right. :-)

      -sauoq
      "My two cents aren't worth a dime.";