Apr 12, 2008

Perl Variables

Perl Variables

Describes the three types of Perl variables and provides examples of Perl variable use.

Variable Indications and types

Three types of perl variables are:

  1. Scalar designated by $.
  2. Array designated by @.
  3. Hash or associative array indicated by %.

The "$" sign indicates scalar variables. They do not need to be declared before they are used. For instance the line:

$myprog = "/usr/bin/progname";

Sets the variable, $myprog to the string value of "/usr/bin/progname" which is the path and name of a program. The line:

$j = 10;

sets the variable $j to a value of 10.

Variable Manipulation

Strings

The "." symbol or period causes one string to be added or concatenated to another. Therefore given the following example:

$X = "Hi ";
$Y = "there!";
$X = $X . $Y;

The last statement will take the contents of $X and $Y and place them in $X which is now "Hi there!". A shorthand way to add them is:

$X .= $Y;

This statement performs the same function as the third line above. The value of $X can be seen with the following command:

print $X;

Arrays

Arrays are created as follows:

@tags = ( 'FORM', 'TABLE', 'OL', 'UL');

The statement:

print $tags[0, "\n"];

prints the string "FORM". The string table is referred to with the $tags[1] reference and so on. The statement:

Print $#tags, "\n";

Will print the largest index value of the array which is 3 in this case, therefore looping for all values in the array may be done as follows:

for ($i = 0; $i < = $#tags; $i++)
{
   print $tags[$i], "\n";
}

This will print all the values in the array on separate lines. Another way to do this is:

foreach $i (@tags)
{
   print $i, "\n";
}

The "foreach" command will place each element of the array @tage in $i until all elements have been used.

Hash

Hashes are similar to arrays (hashes are also called associative arrays), but contain the data in pairs called a KEY and associated VALUE. Hashes are designated with the '%' sign rather than the '@' as in an array. The {} brackets are used to reference elements in the hash rather than the [] brackets as in normal arrays. Please note that the () brackets are used to create the hash or array.

%group = ('forest', 'tree', 'crowd', 'person');
print "A $group{'forest'} is in the forest.\n";  #A tree is in a forest.

Adding elements to a hash can be done with either of the following methods:

%group = (%group, 'fleet', 'ship');
$group{'herd'}='cow';

A list argument can be used to create the hash as follows:

%group = (
        forest -> 'tree',
        crowd -> 'person',
        fleet -> 'ship',
        herd -> 'cow'
);

Two hash variables may be combined into one as follows:

%group1 = ('forest', 'tree', 'crowd', 'person');
%group2 = ('herd', 'cow', 'fleet', 'ship');
%group = (%group1, %group2);

A hash can be printed as follows:

print “@{[%group]}\n”;

No comments:

Post a Comment

Popular Posts