In this third part of a five-part series on scalars in Perl, we continue our study of operators, moving on to Boolean and string operators. This article is excerpted from chapter two of the book Beginning Perl, written by James Lee (Apress; ISBN: 159059391X).
Finally, you can flip the number completely, and replace all the 1s by 0s and vice versa. This is done with the not, or ~, operator:
85 01010101 170 10101010
Let’s see, however, what happens when we try this in Perl:
#!/usr/bin/perl -w # bitop2.pl
print "NOT 85 is ", ~85, "\n";
Depending on the computer, the answer might be
$ perl bitop2.pl NOT 85 is 4294967210 $
Your answer might be different, and we’ll explain why in a second.
Why is it so big? Well, let’s look at that number in binary to see if we can find a clue as to what’s going on:
4294697210 11111111111111111111111110101010
Aha! The last part is right, but it’s a lot wider than we’re used to. That’s because the previous examples only used 8 bits across, whereas many computers store integers as 32 bits across, so what’s actually happened is this:
If you get a much bigger number, it’s because your computer represents numbers internally with 64 bits instead of 32, and Perl has been configured to take advantage of this.
Truth and Falsehood
True and false are important in Perl. In Perl, false is defined as
0
“0”
“” (also known as the empty string)
Undefined
Empty list (we’ll discuss this in Chapter 4)
Later, we will want to perform actions based on whether something is true or false, like if one number is bigger than another, or unless a problem has occurred, or while there is data left to examine. We will use comparison operators to evaluate whether these things are true or false so that we can make decisions based on them.
Some programming languages represent false as 0 and true as 1, and this allows us to use operators very similar to those bitwise operators we’ve just met to combine our comparisons, and to say “if this or this is true,” “if this is not true,” and so on. The idea of combining values that represent truth and falsehood is called Boolean logic, after George Boole, who invented the concept in 1847, and we call the operators that do the combining Boolean operators.