linux poison RSS
linux poison Email

Perl Script: Creating key-value pair (hash table) using Associative arrays

Associative arrays are a very useful and commonly used feature of Perl.

Associative arrays basically store tables of information where the lookup is the right hand key (usually a string) to an associated scalar value. Again scalar values can be mixed ``types''.

Below simple script demonstrate the usage of associative array and shows all the possible operation that can be done on this associative array.

Source: cat

# Creating Associative Arrays
%array = ("a", 1, "b", 2, "c", 3, "d", 4);

# Add more elements to the array
$array{"e"} = 5;

# Get all the keys.
@keys = sort keys(%array);
print "Keys present in the arrays are: @keys \n";

# Get all the values.
@values = sort values(%array);
print "Values present in the arrays are: @values \n";

# Get the value by referring to the key.
print "Enter the value between: ";
$getvalue = <STDIN>;
print "value present for the $getvalue: $array{$getvalue} \n";

# Loop though the array
foreach $key (sort(keys(%array))) {
        print "$key : $array{$key} \n";

# Delete the key-value pair

# Copy associative array to normal array.
@array1 = %array;
print "Now the normal array contains: @array1 \n";

Output: perl
Keys present in the arrays are: a b c d e 
Values present in the arrays are: 1 2 3 4 5 
Enter the value between: e
value present for the e: 5 
a : 1 
b : 2 
c : 3 
d : 4 
e : 5 
Now the normal array contains: e 5 c 3 b 2 d 4 


Post a Comment

Related Posts with Thumbnails