01Apr2009

Using Numbers and Strings in Perl

In Perl, numbers and strings are called scalars. Scalars that do not change during the lifetime of a program are known as constants or literals. Scalars that do change are known as variables. Operators do something with scalars, for example, add together the contents of two variables.

Literals/Constants

There are two types of literal:

  • numeric literals, for example, 6, 8.5, 11, 17.678, and so on, and
  • string literals, for example, "hello world".

Numeric literals may be integers, for example, 6, floating point, for example, 12.5, or scientific notation, for example, 2e10. Strings are a sequence of characters, for example, goodbye cruel world.

Scalar Variables

Data that may change during the lifetime of a program is stored in variables, for example, $total. The dollar ($) sign is called a type identifier, and tells Perl that the variable contains scalar data.

Variable names can contain alphanumeric characters (a-z, A-Z, and 0-9) and the underscore character, and are case-sensitive.

Expressions and Operators

Perl programs are collections of expressions and statements that, by default, are executed in the order in which they appear in the program.

1. #!/usr/bin/perl -w
2. $radius=10;
3. $pi=3.1415927;
4. $area=$pi*($radius**2);
5. print $area;

The equals sign (=) is known as the assignment operator. It takes the value on its right-hand side, and puts it in the variable on the left. The star (*) is the multiplication operator. Two stars together (**) indicate 'to the power of'.

Another example:

1. $a="Goodbye";
2. $b="cruel world";
3. $c=$a.$b;
4. print $c;

The dot (.) concatenates the contents of variables $a and $b, and the result is put into variable $c.

About the Author: John Dixon is a web developer working through his own company John Dixon Technology Limited. The company also develops and supplies a free accounting software tool called Earnings Tracker. The company's web site contains various articles, tutorials, news feeds, and a finance and business blog.

0 comments:

Post a Comment