Web Solutions-Open Source CPAN 561

Lecture 2: Lists, Arrays, Associative Arrays, and Hashes

Lists and arrays:

A list is a sequence of scalar values enclosed in parentheses. The following is a simple example of a list:

(1, 5.3, "hello", 2);

This list contains four elements, each of which is a scalar value: the numbers 1 and 5.3, the string hello, and the number 2.

Lists can be as long as needed, and they can contain any scalar value or scalar variable. A list can have no elements at all, as follows:

()

This list also is called an empty list.

An array variable is a memory storage for more than one value. Each value is uniquely identified by its index. The array name starts with the character @. This enables perl to distinguish arrays from other kind of variables.

Arrays are used to store a list. For example:

@array=(1,35,100);

or

@myarray=(1..20);

The statement

print “@array “;

will print 1 35 100

To assign the second element of @myarray to a scalar variable, we may code :

$var=$myarray[1];

If you try to access a non existing array element, then perl will use null for this element. Remember that array index in perl start from (0). Therefore $var is considered null in the following example:

$var=$myarray[-1];

Also notice that we can use an array within another array list:

@arr1=(5,10,15,20);

@arr2=(1,@arr1,50);

here @arr2 will have the list (1,5,10,15,20,50)

In order to determine the length of a list in an array we use :

$scalar = @array;

Notice that this statement is different from the statement:

($scalar) = @array;

Here, the first element of @array is assigned to $scalar.

List may be also used to extract values from an array. For example:

@array =(“john smith”,21,”main street”);

($name,$age,$address)=@array;

Perl also allows slicing an array. For example:

print @array[0,2];

will print the john smith main street

As another example:

($name,$address)=@array[0,2];

Here we assign the first and the third array elements to scalar variables $name and $address consequently.

The statement

@subArr=@array[0,2];

Will slice two elements from @array (first and third) and store them in another array called @subArr.

Arrays library functions:

  • sort:

This function sorts the elements of an array in alphabetical order and returns the sorted list. For example:

@array = ("b", "c", "a", "d");

@array1 = sort (@array);

After sort is called, the value of @array1 is the list

("a", "b", "c", "d")

Note that sort treats its items as strings. Items are sorted in alphabetical, not numeric, order. For example:

@arr = (10, 12, 5,20);

@arr = sort (@arr);

In this case, sort produces (10,12, 20,5)

  • reverse:

This function reverses the order of the elements of a list or array variable, and returns the reversed list. For example:

@array = ("b", "c", "a", "d");

@array1 = reverse (@array);

After sort is called, the value of @array1 is the list

("d", "a", "c", "b")

  • chop:

This function is used to remove the last character from all elements of an array. For example:

@arr = ("first", "12345", "match");

chop (@arr);

The list stored in @arr is ("firs", "1234", "matc").

  • join:

This function is used to merge the elements of an array into a single string. For example:

@array=(“a”,”b”,”c”,”d”);

$var = join (“,”,@array);

  • split:

This function is used to split a string into array elements. For example:

$var = "first,second,third";

@array = split(/,/, $var);

  • push:

This function takes an array and a list of elements to append them to it. It returns the new length of the array. For example:

@arr=(1,2,3,5);

$newlength=push @arr, (10,20);

The new length of the array will be 6.

  • pop:

This function moves the last element in an array and returns that element. If the array is empty it returns udef. For example:

@arr=(1,2,3,5);

$element=pop @arr;

$element will contain 5, and the array will contain 3 elements only after that.

  • unshift:

This function work like push function, but the elements are added at the beginning of the array.

  • shift:

This function work like pop function, but the elements are moved from the beginning of the array.

Associative arrays:

An associative array is another kind of array, which its subscript can be any scalar value. The associative array variable name is prefixed with the character %. To distinguish between an associative array and ordinary array, subscripts for associative array elements are always enclosed in brace brackets. The elements of an associative array are not guaranteed to be in any particular order. We can declare an associative array using one of the two following syntaxes

%arr=("first", 57, "second", 119, "third", "blue");

or

%arr = ("first" => 57, "second" => 119, "third" => "blue");

To add an element to an associative array, assign the new element to subscript that is not previously used:

$arr{"fourth"} = “home”;

To delete an element, we use the built-in function delete:

delete($arr{"home"});

To traverse through an associated array we can use the built-in function keys with foreach statement. For example:

foreach $key(keys %arr)
{
print "subscript is $key, and value is $arr{$key}<br>";
}

Also we can use the build in function each. This function returns a two-element list. The first element is the subscript for a particular element of the associative array, and the second element is the value associated with that subscript. For example:

while (($key,$value)=each (%arr))
{
print "subscript is $key, and value is $value <br>";
}

Hashes:

A hash can be thought of as a two column table. The left column stores keys and the right column stores their associated values.

A hash variable is prefixed with % and initialized with a list. For example:

%myHash=(“one”=>”first”,”two”=>”second”,”three”=>”third”);

The individual values in a hash are called entries, and accessed by specifying the key. For example:

Print $myHash{“one”};

Perl provides three methods to iterate a hash.

  • keys:

This function take a hash as its argument and returns a list of its keys in random order. For example:

foreach $key (keys %myHash)
{
print "the key $key has $myHash{$key} <br>";
}

  • values:

This function take a hash as its argument and returns a list of its values in random order.

foreach $value (values %myHash)
{
print "$value <br>";
}
each:

This function take a hash as its argument and returns a list of key/value pairs.

while(($key,$value)=each %myHash)
{
print "the key $key has $value <br>";
}

Perl allows slicing hashes. For example, instead of coding

Print “$myHash{“one”}, $myHash{“two”}, $myHash{“three”}”;

We can code:

Print “@myHash{“one”,“two”,“three”}”;

Also we can code:

@myHash{“four”,”five”}=(“fourth “,”fifth”);

print @myHash{“one”,”five”};

Examples:

Ex1: arr.cgi

#!c:/perl/bin/perl
print "Content-Type: text/html\n\n";
$var="John Smith";
@myArr=("$var",20,"123 main street");
print "<html>\n <title> \n array \n </title>\n";
print "<body>\n";
foreach $value (@myArr)
{
print "$value <br>";
}
print "</body>";
print "</html>";

Following is a screenshot of the output:

Ex2: random.cgi

#!c:/perl/bin/perl
print "Content-Type: text/html\n\n";
print "<html>\n <title> \n random \n </title>\n";
print "<body>\n";
$i=0;
@myrand;
until($i==10)
{
$myrand[$i]=int(rand(50));
$i=$i+1;
}
foreach $x (@myrand){
print "$x<br>";
}
print "</body>";
print "</html>";

Following is a screenshot of the output:

Ex3: arrfunctions.cgi

#!c:/perl/bin/perl
print "Content-Type: text/html\n\n";
@myArr=("a","d","b","c");
print "<html>\n <title> \n array \n </title>\n";
print "<body>\n";
print "original array<br>";
foreach $x (@myArr)
{
print "$x<br>";
}
print "sorted ";
@sarr=sort(@myArr);
print "sorted array<br>";
foreach $x (@sarr)
{
print "$x<br>";
}
@rarr=reverse(@myArr);
print "reversed array<br>";
foreach $x (@rarr)
{
print "$x<br>";
}
$var=join(",",@myArr);
print "joined array elements to a string :$var<br>";
print "split the string back to an array<br>";
@newArr=split(",",$var);
foreach $x (@newArr)
{
print "$x<br>";
}
print "</body>";
print "</html>";
Following is a screenshot of the output:

Ex4:pushandpop.cgi

#!c:\perl\bin\perl
print "Content-type: text/plain\n\n";
@arr=(1,2,3,5);
$len=@arr;
print "the original length of the array is $len \nthe original array elements:\n";
foreach $x (@arr)
{
print "$x\n";
}
$newLength=push @arr, (10,20);
print "the new length of the array is $newLength \n";
foreach $x (@arr)
{
print "$x\n";
}
while ($nextElement=pop @arr)
{
print "last element in the array is $nextElement\n";
}

Following is a screenshot of the output:

Ex5:shiftandunshift.cgi:

#!c:\perl\bin\perl
print "Content-type: text/plain\n\n";
@arr=(1,2,3,5);
$len=@arr;
print "the original length of the array is $len \nthe original array elements:\n";
foreach $x (@arr)
{
print "$x\n";
}
$newLength=unshift @arr, (10,20);
print "the new length of the array is $newLength \n";
foreach $x (@arr)
{
print "$x\n";
}
while ($nextElement=shift @arr)
{
print "last element in the array is $nextElement\n";
}

Following is a screenshot of the output:

Ex6:assArr.cgi:

#!c:/perl/bin/perl
print "Content-Type: text/html\n\n";
print "<html>\n <title> \n hash \n </title>\n";
print "<body>\n";
%arr=(one=>"first",
two=>"second",
three=>"third");
print " The associative array before adding new element <br>";
foreach $key(keys %arr)
{
print "subscript is $key, and value is $arr{$key}<br>";
}
$arr{"four"}="fourth";
print " <br>The associative array after adding new element <br>";
while (($key,$value)=each (%arr))
{
print "subscript is $key, and value is $value <br>";
}
delete($arr{"two"});
print " <br>The associative array after deleting one element <br>";
while (($key,$value)=each (%arr))
{
print "subscript is $key, and value is $value <br>";
}
print "</body>";
print "</html>";

Following is a screenshot of the output:

Ex7:hash.cgi:

#!c:/perl/bin/perl
print "Content-Type: text/html\n\n";
print "<html>\n <title> \n hash \n </title>\n";
print "<body>\n";
%myHash=(one=>"first",
two=>"second",
three=>"third");
foreach $key(keys %myHash)
{
print "the $key has a value $myHash{$key}<br>";
}
@myHash{"four","five"}=("fourth","fifth");
print @myHash{"one","five"};
print "</body>";
print "</html>";

Following is a screenshot of the output:

1