10.07.2015 Views

Beginning Web Development With Perl : From Novice to ... - Nabo

Beginning Web Development With Perl : From Novice to ... - Nabo

Beginning Web Development With Perl : From Novice to ... - Nabo

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

296APPENDIX ■ PERL BASICSThe last arithmetic opera<strong>to</strong>r remainder, or modulo opera<strong>to</strong>r. This calculates the remainderwhen one number divides another. For example, 6 divides in<strong>to</strong> 15 twice, with a remainderof 3, as our next program will confirm:#!/usr/bin/perl -w# arithop8.plprint "15 divided by 6 is exactly ", 15 / 6, "\ n";print "That's a remainder of ", 15 % 6, "\ n";$ perl arithop8.pl15 divided by 6 is exactly 2.5That's a remainder of 3$The modulo opera<strong>to</strong>r has the same precedence as multiply and divide.Bitwise Opera<strong>to</strong>rsUp <strong>to</strong> this point, the opera<strong>to</strong>rs worked on numbers in the way we think of them. However, aswe already know, computers don’t see numbers the same as we do; they see them as a string ofbits. These next few opera<strong>to</strong>rs perform operations on numbers one bit at a time—that’s whywe call them bitwise opera<strong>to</strong>rs. These aren’t used quite so much in <strong>Perl</strong> as in other languages,but we’ll see them when dealing with things like low-level file access.First, let’s have a look at the kind of numbers we’re going <strong>to</strong> use in this section, just so weget used <strong>to</strong> them:• 0 in binary is 0, but let’s write it as 8 bits: 00000000.• 51 in binary is 00110011.• 85 in binary is 01010101.• 170 in binary is 10101010.• 204 in binary is 11001100.• 255 in binary is 11111111.Does it surprise you that 10101010 (170) is twice as much as 01010101 (85)? It shouldn’t—when we multiply a number by 10 in base 10, all we do is slap a 0 on the end, so 21 becomes210. Similarly, <strong>to</strong> multiply a number by 2 in base 2, we do exactly the same.People think of bitwise opera<strong>to</strong>rs as working from right <strong>to</strong> left; the rightmost bit is calledthe least significant bit and the leftmost is called the most significant bit.The AND Opera<strong>to</strong>rThe easiest bitwise opera<strong>to</strong>r <strong>to</strong> fathom is called the AND opera<strong>to</strong>r, and is written &. This comparespairs of bits as follows:• 1 and 1 gives 1.• 1 and 0 gives 0.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!