Mar 20, 2002, 7:05 AM
Post #3 of 9
Re: [Coderifous] Rarely Used Operators:
[In reply to]
I sort of understand the bit shift operators (>> and <<), in that they shift binary values like: 2 << 3 makes "000010" become "010000" or 2 becomes 16. I get that. But can anyone give me some practical uses of it in code examples? And how does "print <<EOF;" or "$this = <<END;" make use of this operator? I understand how they work in this context, but I don't understand why... is it basically a totally unrelated operator in this context?
The heredoc operator is totally unrelated to the bitshift operators, although it looks exactly like the shift-left-operator.
And the ~ operator is a logical 'or-ing' operator? so on a 32 bit machine:
will output: 4294967294
which is the basically taking: 00000000000000000000000000000001
and turning it into: 11111111111111111111111111111110
Nope, it's not a logical OR (this would be '||' or 'or'), it's a binary NOT (negation) operator. It will just complement each bit, as your example above shows.
But what would you use it for? What practical applications could it serve?
You use it, well, basically when you need the complement of an integer...
I usually use it when I need to clear bits:
$var = 0xdead;
$bit = 3; # counting starts at zero
$var |= 1<<$bit; # set a bit
$var &= ~(1<<$bit); # clear a bit
(Don't blame me for the above, I would rarely use such code in Perl, and in C I would hide it inside some macros...)
I've seen Marcus use it as a cool way to test against the length of a hash:
print "it's 7" if ~~%hash == 7;
but aside from forcing things into the context of numbers by double-or-ing them, what would you use that operator for?
I didn't write the above piece of code, or did I? If so, please point me to the post, I must have been really sick then...
I have, however, used ~~ as a short way of writing int, although you could also use it in some cases as a short form of scalar. In the above code line, the ~~ doesn't make any sense, because %hash is already forced into scalar context by the == operator.
At last with an effort he spoke, and wondered to hear his own words, as if some other will was using his small voice. "I will take the Ring," he said, "though I do not know the way."