home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam  


Book HomeLearning Perl, 3rd EditionSearch this book

2.2. Numbers

Although a scalar is most often either a number or a string, it's useful to look at numbers and strings separately for the moment. We'll cover numbers first, and then move on to strings.

2.2.4. Nondecimal Integer Literals

Like many other programming languages, Perl allows you to specify numbers in other than base 10 (decimal). Octal (base 8) literals start with a leading 0, hexadecimal (base 16) literals start with a leading 0x, and binary (base 2) literals start with a leading 0b.[45] The hex digits A through F (or a through f) represent the conventional digit values of ten through fifteen. For example:

[45]The "leading zero" indicator works only for literals -- not for automatic string-to-number conversion, which we'll see later in this chapter. You can convert a data string that looks like an octal or hex value into a number with oct( )or hex( ). Although there's no "bin" function for converting binary values, oct( )can do that for strings beginning with 0b.

0377       # 377 octal, same as 255 decimal
0xff       # FF hex, also 255 decimal
0b11111111 # also 255 decimal (available in version 5.6 and later)

Although these values look different to us humans, they're all three the same number to Perl. It makes no difference to Perl whether you write 0xFF or 255.000, so choose the representation that makes the most sense to you and your maintenance programmer (by which we mean the poor chap who gets stuck trying to figure out what you meant when you wrote your code. Most often, this poor chap is you, and you can't recall whay you did what you did three months ago).

When a non-decimal literal is more than about four characters long, it may be hard to read. For this reason, starting in version 5.6, Perl allows underscores for clarity within these literals:

0x1377_0b77
0x50_65_72_7C


Library Navigation Links

Copyright © 2002 O'Reilly & Associates. All rights reserved.