Chapter 15. Working with Bits

Perl is a high-level language, so I don’t have to play with bits and bytes to get my job done. The trade-off, however, is that I have to let Perl manage how it stores everything. What if I want to control that? And what about the rest of the world, which packs a lot of information into single bytes, such as Unix file permissions? Or what if my array of tens of thousands of numbers takes up too much memory? Falling back to working with the bits can help that.

Binary Numbers

Almost all of us deal with binary computers, even to the point that it seems redundant to say “binary.” When it gets down to the lowest levels, these deal with on or off, or what we’ve come to call 1 or 0. String enough of those 1s and 0s together, and I have the instructions to tell a computer to do something or the physical representation of data on a disk. And, although most of us don’t have to deal with computers at this level, some of this thinking has reached into high-level programming because we have to deal with lower levels at some point.

Consider, for instance, the arguments that I use with mkdir, chmod, or dbmopen to set the file mode (also known as permissions, but it’s actually more than just that). Although I write the mode as a single base-8 number, its meaning depends on its particular bit pattern:

mkdir $dir, 0755;
chmod 0644, @files;
dbmopen %HASH, $db_file, 0644;

I also get the file mode as one of the return values from stat:

my $file_mode = ( stat( $file ...

Get Mastering Perl, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.