Home Perl Programming Page 5 - Perl: Number Crunching

# Proselytizing Numbers into Holy Strings! - Perl

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.

By: James Payne
Rating:  / 6
August 05, 2008

SEARCH DEV SHED

TOOLS YOU CAN USE

Converting numbers into strings is pretty simple in Perl. Here is an example showing just how to do so:

#!/usr/bin/perl

\$ravioli = 150;

\$ravioli = \$ravioli . " Meatballs on my plate. Yum.";

print \$ravioli;

This will print out the following text:

150 Meatballs on my plate.

Pretty simple. Now let's see what happens when we add math into the mix:

#!/usr/bin/perl

\$ravioli = 150;

print \$ravioli * 10;

\$ravioli = \$ravioli . " Meatballs on my plate. Yum.\n";

print \$ravioli * 10;

For me, this code does something very odd. At first it prints the 1500, as it should. Then, for some reason, it prints 1500 again, when it should print the 150 Meatballs sentence ten times. This is a known problem with converting numbers to strings; if you try to perform numbers on them after the conversion, it won't necessarily work. For all of you nay-sayers, here is a little more code to prove my point:

#!/usr/bin/perl

\$ravioli = 150;

print \$ravioli * 10;

\$ravioli = \$ravioli . " Meatballs on my plate. Yum.\n";

print \$ravioli * 10;

print \$ravioli;

The result?

15001500150 Meatballs on my plate. Yum.

As you can see, the value was converted, but when we applied math to it, it went nuts and thought it was still a number.

Well that's all the time we have for this article. Come back next time for more Perls of wisdom. Till then...

 >>> More Perl Programming Articles          >>> More By James Payne