Home arrow Perl Programming arrow 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.

TABLE OF CONTENTS:
  1. Perl: Number Crunching
  2. Smooth Operator
  3. Operator Precedence
  4. The Positive and the Negative
  5. Proselytizing Numbers into Holy Strings!
By: James Payne
Rating: starstarstarstarstar / 6
August 05, 2008

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

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
 

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort
   

PERL PROGRAMMING ARTICLES

- Perl Turns 25
- Lists and Arguments in Perl
- Variables and Arguments in Perl
- Understanding Scope and Packages in Perl
- Arguments and Return Values in Perl
- Invoking Perl Subroutines and Functions
- Subroutines and Functions in Perl
- Perl Basics: Writing and Debugging Programs
- Structure and Statements in Perl
- First Steps in Perl
- Completing Regular Expression Basics
- Modifiers, Boundaries, and Regular Expressio...
- Quantifiers and Other Regular Expression Bas...
- Parsing and Regular Expression Basics
- Hash Functions

Developer Shed Affiliates

 


Dev Shed Tutorial Topics: