1. Introduction
Scalar variable allows us to store scalar wich is a number or a string.
Array variable allows us to store a collection of scalars.
We can access each scalar data in array by using indices.
Hash variables (associative arrays before) allows us to store
collective data type as an array does.
Each element of a hash has two parts: key and value or key-value pair.
We access an element of a hach by keys
To define a hash variable, we use percentage sign (%) as follows:
%hash = ("keys" => "values");
Example:
--------
%books = (
"Physics" => "203",
"Mathematics" => "305",
"Chemistry"=> "407"
);
2. Accessing un element of %hash
The sytax is:
%hash {key};
print $books{"Mathematics"};
Outputs:
305
Remark:
We can assign an hash to an array and vice versa.
@hash = %hash;
or
%hash = @hash;
3. Adding Hash elements
To add hash elements, add a line as follows:
%books = (
"Physics" => "203",
"Mathematics" => "305",
"Chemistry"=> "407"
);
$books {"Geography"} = "509";
4. To test whether a key exists
To test whether a key exists in a hash, we use exist() function as folllow:
if ( exists $hash{key} ){
# ... some code goes here ..
}
Example:
if(exists $books{"Geography"}){
print "This discipline exists .."};
5. Removing keys from a Hash
To remove a key from a hash, we use delete function as follows:
delete $hash{key};
To remove all keys and values from a hash, just assign hash to an empty list:
%hash = ();
6. Looping through a Hash
The syntax is:
foreach $element (keys %hash){
# ... some code goes here ..
}
Example:
#!c:\www\Perl\bin
%books = (
"Physics" => "203",
"Mathematics" => "305",
"Chemistry"=> "407"
);
foreach $book (keys %books){
print "$book \n";
}
foreach $book (values %books){
print "$book \n";
}
outputs:
C:\www\PERL>test.pl
Chemistry
Physics
Mathematics
407
203
305
|