In this tutorial we will look at working with numbers in Perl. We'll cover the basics, such as integers and floating points, and end with the more advanced topics, like converting strings to numbers. With Perl you don't need to be a math genius. These simple tips can help you be a virtual Einstein.
The year was...well I don't know exactly what year it was. But there stood Pythagoras of Samos, the great Greek magician and founder of the religion, Pythagoreanism, which is almost as wacky as Scientology, except L. Ron Hubbard didn't name it Hubbardism. You probably know this Greek bad-ass as the guy who made you fail all your math classes when you couldn't tell your professor what the Pythagorean Theorem was.
At any rate, there he stands, and next to him is Hipassus of Metapontum, who takes a sip of his Mountainus Dewus and says, "Hey...I discovered this thing called irrational numbers." He then went on to explain them to Pyth, who, well, got really Pythed off, exclaimed he would not accept the existence of irrational numbers, and sentenced Hippasus to death by drowning.
So what's my point in telling you all that? Numbers are best left to those that know them well, and hardly anyone knows them better than computers. Sometimes this can make working with math in programs difficult, because some are real finicky about how you do your equations. But not our boy Perl (who by the way, has a very effeminate name). Perl makes math simple. Whereas in some languages you have to differentiate between the data types of the math you are performing, in Perl there is no need. And while that might not make sense right this minute, it will very shortly.
Enough rambling. As Morpheus says to Neo in the Matrix...Damn these are some good biscuits.
These Numbers Be Keeping It Real
In the world of computers there are two types of numbers: integers and floating-point numbers (also known as real numbers, hence my witty headline). Floating point numbers are decimals, while integers are whole numbers.
In the majority of programming languages, you need to differentiate between floating point and integer numbers. Perl, however, is a math magician. When you type in the number 49, it says, "Hey...that's an integer." If you type in 2.7, then again Perl uses its massive brain to explain to the computer that that number is a floating point.
Here is some sample code showing how to declare integer and floating point variables:
#!/usr/bin/perl
$real=7.11;
$regetni=8;
print "This numba be keepsin it real: " . $real;
print "\n This is an integer: " . $regetni;
As you can see, you do so the same way. Here is the result: