Home Index

Start with Perl, Part II, Variable types in Perl language
 
Date: April  01 2001
Subject: Online Programmer Ezine, Volume 2, No.4
Article: Start with Perl CGI now!, Part II - Variable types in Perl Language

 

In previous part of "Start with Perl" we saw how we can 
write a small Perl cgi script and run it on a web server. 
In this issue we want to speak about variables in Perl 
language.

There are three types of variables in Perl language: 
scalars, arrays and associative arrays. First let's speak 
about scalar type.

Numbers and strings can be stored in a scalar type 
variable. Scalar type variables start with a '$' sign. 
Perl automatically converts between numbers and strings as 
required. Look at this example (comments will come after 
each statement) :

Example 1:

#!/usr/bin/perl
$a=2;
$b=6;
$m='How';
$n=' are you';
$o=$m.$n; 
# Above statement concatenates two strings
$c=$a.$b;
# This one also concatenates two strings but,
# first converts them to string
$d=$c/2;
# In above line string is first converted to number
print $o;
print "\n";
print $d; 


Output result is:

How are you
13


You can run above example in command line but not in a web 
server because we have not added html headers etc.

You can also use "Winperl" by Maxwell Nairin Andrews. It 
has a simple IDE and runs Perl programs inside its IDE. It 
is a very useful tool for learning Perl.

Now let's have a look at arrays.

Arrays are a collection of scalars. Array variable names 
start with '@' sign. 

Look at below example to see how we can assign values to 
arrays.

@langs=("english","german","french");

Array members can be used directly. You can either modify or
read the value of each member easily. But this time you must
use sign for scalar type before the name.

$langs[0], $langs[1], $langs[2]

You can even mix scalar values in an array: 

Example 2:

@myarray=(21,"hello",'33');
print "First one is $myarray[0] while next is $myarray[1]\n";
print "Third one is $myarray[2]";

Output is:

First one is 21 while next is hello
Third one is 33

And now let's see associative arrays:

Associative arrays are a list of values indexed by 
subscripts. Variable name for this type must start with '%' 
sign.

Example 3:

%members=("First","John","Second","Marry","Third","Richard");
print $members{"First"};

Output is:

John

It's enough for this issue. We will see more complex examples
in next issue. In this issue we did not write CGI programs 
but we need this information before we can write CGI programs. 
Until next issue, goodbye!

If you have any question about Perl and cgi programming you 
can ask it in our programming forums.

http://op.htmsoft.com/forums



Home Index
© 2001 OnlineProgrammer (HtmSoft.com) . All Rights Reserved