Next: Program Control
Up: CGI Scripts with Perl
Prev: Basics

Variables

There are three main kinds of variables:

Strings and Numbers

Perl distinguishes between numerical and string data by context. Thus,

$x = 1.9;
$y = $x + 2;

$s = "The answer is ".$y;   # . is the string concatenation operator

print "$s \n";              # substitute the variable inside the quotes

works just fine.

Arrays

Array variables are denoted @x.

Note that the entries in the array must be numerical or string data, so we must refer to them as $x[i], etc. Note also that the subscript is in brackets.

You create an array by storing a value in one of its entries.

$x[1] = "dog";
$x[5] = "cat";        #@x = ( ,"dog", , ,"cat")

@y = @x;              #copy the whole array

print $y[5], "\n";    #print two things

print @x, "\n";       #print the whole array

Associative Arrays

Associative arrays are like standard arrays, except that the objects are indexed by strings.

Associative array variables are denoted %x, and individual entries are accesed as $x{"key"}.

$x{"p"} = "Pear";
$x{"a"} = "Apple";
$x{"o"} = "Orange";

%y = %x;

print $y{"a"},"\n";

print sort(keys(%y)), "\n";   #keys returns an array with the keys,
                              #sort sorts...


Next: Program Control
Up: CGI Scripts with Perl
Prev: Basics

[HOME] The Geometry Center Home Page

Comments to: webmaster@geom.umn.edu
Created: May 07 1996 --- Last modified: May 29 1996