Presenting Mathematical Concepts on the World Wide Web
Forms & Scripts
Perl: Variables
There are three main kinds of variables:
- $x = string or numerical data
- @x = an integer indexed array starting at 0
- %x = an associative array
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 the second entry AND
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
Back: Basics
Up:
Forms & Scripts
Presenting Mathematical Concepts on the World Wide Web.
Copyright © 1997 by
Carol Scheftic.
All rights reserved.
(This section was originally copyrighted in 1996 by
The Geometry Center
and is re-used here with permission.)
Please send comments on this page,
or requests for permission to re-use material from this page, to:
scheftic@geom.umn.edu
Page established 1-Jun-97;
last updated Monday, 28-Jul-1997 11:54:23 CDT.