Perl Programming Page 2 - Scalars |
There are two types of number that we are interested in as Perl programmers: integers and floating point numbers. The latter we’ll come to in a minute, but let’s work a bit with integers right now. Integers are whole numbers with no numbers after the decimal point like 42, –1, or 10. The following program prints a couple of integer literals in Perl. #!/usr/bin/perl -w print 25, -4; $ perl number1.pl Well, that’s what you see, but it’s not exactly what we want. Fortunately, this is pretty easy to fix. Firstly, we didn’t tell Perl to separate the numbers with a space, and secondly, we didn’t tell it to put a new line on the end. Let’s change the program so it does that: #!/usr/bin/perl -w print 25, " ", -4, "\n"; This will do what we were thinking of: $ perl number2.pl25 -4 $ For the purpose of human readability, we often write large integers such as 10000000 by splitting up the number with commas: 10,000,000. This is sometimes known as chunking. While we might write 10 million with a comma if we wrote a check for that amount, don’t use the comma to chunk in a Perl program. Instead, use the underscore: 10_000_000. Change your program to look like the following: #!/usr/bin/perl -w print 25_000_000, " ", -4, "\n"; Notice that those underscores don’t appear in the output: $ perl number3.pl As well as integers, there’s another type of number—floating point numbers. These contain everything else, like 0.5, –0.01333, and 1.1. Note that floating point numbers are accurate to a certain number of digits. For instance, the number 15.39 may in fact be stored in memory as 15.3899999999999. This is accurate enough for most scientists, so it will have to be for us programmers as well. Here is an example of printing the approximate value of pi: #!/usr/bin/perl -w print "pi is approximately: ", 3.14159, "\n"; Executing this program produces the following result: $ perl number4.pl
blog comments powered by Disqus |
|
|
|
|
|
|
|