Home Perl Programming Page 3 - Perl: Number Crunching

# Operator Precedence - 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

In Perl, and I believe pretty much most of the languages out there, you give precedence to an equation by encapsulating it in parentheses. Consider the following:

5 + 9 * 2 = 28

5 + (9 * 2) = 23

By wrapping the equation 9 * 2 in parentheses, we force it to be calculated first, giving a different result. Even though you don't deserve it, here it is in code:

#!/usr/bin/perl

\$complex = (9*2) - (2*9) + (180/10) * 10 * (2 * 5) / 100;

print \$complex;

This gives us the result:

18

Exponentially Yours

The exponential operator (**) allows you to get the power of a number. For instance, 5**100 is 5 to the hundredth power, or 7.88860905221012e+069. Or simply put, some ridiculously crazy number. Something simpler to comprehend might be 3**3, which is 3 to the third power or 3 * 3 * 3 (which of course equals 27). Here it is in code:

#!/usr/bin/perl

\$power = 0**10;

\$powera = 1**10;

\$powerb = 2**10;

\$powerc = 3**10;

\$powerd = 4**10;

print \$power . "\t" ;

print \$powera . "\t";

print \$powerb. "\t" ;

print \$powerc. "\t" ;

print \$powerd. "\t" ;

And the result is...

0 1 1024 59049 1048576

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