Perl Programming Page 3 - Scalars |
As we saw in the previous chapter, we can express numbers as binary, hexadecimal, or octal numbers in our programs. Let’s look at a program to demonstrate how we use the various number systems. Type in the following code, and save it asgoodnums.pl: #!/usr/bin/perl -w print 255, "\n"; All of these are representations of the number 255, and accordingly, we get the following output: $ perl goodnums.pl When Perl reads your program, it reads and understands numbers in any of the allowed number systems,0for octal,0bfor binary, and0xfor hex. What happens, you might ask, if you specify a number in the wrong system? Well, let’s try it out. Editgoodnums.plto give you a new program,badnums.pl, that looks like this: #!/usr/bin/perl -w print 255, "\n"; Since octal digits only run from 0 to 7, binary digits from 0 to 1, and hex digits from 0 to F, none of the last three lines make any sense. Let’s see what Perl makes of it: $ perl badnums.pl Now, let’s match those errors up with the relevant lines: Illegal octal digit '8' at badnums.pl line 5, at end of line And line 5 is print 0378, "\n"; As you can see, Perl thought it was dealing with an octal number, but then along came an 8, which stopped making sense, so Perl quite rightly complained. The same thing happened on the next line: Illegal binary digit '2' at badnums.pl line 6, at end of line And line 4 is print 0b11111112, "\n"; The problem with the next line is even bigger: Bareword found where operator expected at badnums.pl line 7, near "0xFG" The line starting “Bareword” is a warning (since we are using the-woption). Then it is followed by a syntax error. A bareword is a series of characters outside of a string that Perl doesn’t recognize. The word could mean a number of things, and Perl is usually quite good about knowing what you mean. In this case, the bareword wasG: Perl had understood0xF, but couldn’t see how theGfitted in. We might have wanted an operator do something with it, but there was no operator there. In the end, Perl gave us a syntax error, which is the equivalent of it giving up and saying, “How do you expect me to understand this?”
blog comments powered by Disqus |
|
|
|
|
|
|
|