Saturday, December 27, 2014

Tutorial 5 : Hashes Example

Hey, guys. Welcome back to Cer tutorial. In this tutorial, we will learn the last data type which is existing in Perl language. Hash is a set of key and value pair. This variable is come before with a percent (%) sign. It is very convenient for us, especially get the reference value from the key. 

What is 'key' and 'value'? Key is a variable / memory which is used to store the data / value. When you call the particular key, it will return the stored value for the system. Let's us see how it works.

Hashes

Create and Access Hashes

There are two ways to create hashes. The first method is assign a value to a key with one-by-one basic. Second method is use a list, the first element will be used as the key and second element will be the value of the key. Let's see how it works.

#!/usr/bin/perl

$name{'John'} = 45;           # one-by-one basic
$name{'Ali'} = 50;
%data = ('Car' => 40, 'House' => 100);   # list basic

print "John is $name{'John'} years old\n";
print "Ali is $name{'Ali'} years old\n";
print "Ali is older than John\n";
print "John own a car which is cost $data{'Car'}k\n";
print "Whereas Ali own a house which is cost $data{'House'}k\n";


The video below shows the output of above example.


Extracting Keys and Values

Since we have the keys and value in the hashes, sometimes we might be need to extract the data separately such as want to get the keys or value data only. Let's see how we can perform this operation.

#!/usr/bin/perl

%data = ('John' => 45, 'Ali' => 50, 'Koko' => 35);

@name = keys %data;
@age = values %data;
@slice = @data{'John', 'Koko'};

print "@name\n";
print "@age\n";
print "@slice\n";

The output of this example is shown as video below.


Add and Remove Hashes

In hashes data type, we also can add or remove the elements on it. But the command is different with command which is used in the array. Let's see how we can perform it.

#!/usr/bin/perl

%data = ('Ali' => 45, 'Abu' => 35);
@name = keys %data;
$size = @name;

print "Original : @name\n";
print "Size : $size\n\n";

$data{'Koko'} = 50;
@A_name = keys %data;
$A_size = @A_name;

print "Adding : @A_name\n";
print "Size : $A_size\n\n";

delete $data{'Ali'};
@D_name = keys %data;
$D_size = @D_name;

print "Delete : @D_name\n";
print "Size : $D_size\n\n";

This example should be perform as the video at below.


In the next tutorial, we will learn the conditional statement in Perl language. Have a nice day o.

No comments:

Post a Comment