PERL/C2/Hash-in-Perl/English

From Script | Spoken-Tutorial
Jump to: navigation, search

Title Of Script: Hash in Perl

Author: Amol Brahmankar

Keywords: Hash in perl, Associative Array in Perl video tutorial.


Visual Cue
Narration
Slide Welcome to the spoken tutorial on Hash in Perl.
Slide: Learning Objectives In this tutorial, we will learn about;
  • Hash in Perl and
  • Accessing element of a hash
Slide: System Requirements For this tutorial, I am using
  • Ubuntu Linux12.04 operating system
  • Perl 5.14.2 and
  • gedit Text Editor

You can use any text editor of your choice.

Slide: Prerequisites To practise this tutorial, you should have knowledge of Variables & Data Structures in Perl.


Knowledge of comments, loops, conditional statements and Arrays will be an added advantage.


Please go through the relevant spoken tutorials on the spoken tutorial website.

Slide * Hash is an unordered collection of data
  • It's a key/value pair data structure
  • Hash keys are unique
  • However, Hash can have duplicate values
Slide This is the declaration of a hash .
Let us see how to get the value of a key from hash.
Slide


$hashName{'KeyName'}

The syntax for accessing the value of a key is


dollar hashName open curly bracket single quote keyName single quote close curly bracket

Let us understand hash using a sample program.
Switch to gedit with perlHash.pl opened I have already typed the code in perlHash dot pl file in gedit.
Gedit


#!/usr/bin/perl


%hash = (

'Name' => 'John',

'Department' => 'Finance'

);


print "Value of Key Name is: ", $hash{'Name'}, "\n";

Type the code as shown in your perlHash dot pl file.

<<pause>>





%hash


highlight keys 'Name' & 'Department'


highlight values 'John' & 'Finance'


$hash{'Name'}

Hash in Perl is declared with percentage sign.


These are the keys of hash.


And these are the values of hash.


Note: To access key of hash, one has to use dollar sign.

Slide Press Ctrl + S to save the file.
Switch to terminal


perl perlHash.pl


Then switch to the terminal and execute the Perl script as


perl perlHash dot pl


and press Enter.

Highlight the output on the terminal The output is as shown on terminal. <pause>
Now let us see add and delete of keys from a hash.
Slide The syntax for

1. adding key is

dollar hashName open curly bracket

single quote KeyName single quote

close curly bracket equal to value semicolon

2. deleting key is

delete dollar hashName open curly bracket

single quote KeyName single quote

close curly bracket semicolon

Now, let us understand this using a sample program.
Terminal hashKeyOperations dot pl I have already typed the code in hashKeyOperations dot pl file.
#!/usr/bin/perl

use Data::Dumper;


#Hash of marks obtained in a subject

%hash = (

'Subject' => 'Math',

'Marks' => 98

);


print "Hash before adding keys\n";

print Dumper \%hash;


#Add Name and roll number of a student

$hash{'Name'} = 'Amol';

$hash{'RollNumber'} = 12;


print "Hash after addition of Name & RollNumber keys\n";

print Dumper \%hash;


delete $hash{'RollNumber'};


print "Hash after deletion of RollNumber key\n";

print Dumper \%hash;

This is the declaration of hash.


We'll be adding, deleting the keys from this hash.


Here we are adding a key to an already created hash.

It is like assigning a value to a variable.













delete keyword is used to delete the key.

We need to pass the key to delete it.


Press Ctrl+S to save the file.
Terminal

perl hashKeyOperations.pl

Switch to the terminal and execute the Perl script as


perl hashKeyOperations dot pl


and press Enter.

Highlight the output. Output will be as shown on the terminal.

<<pause>>

Let us look at sorting of a hash keys and values.
Slide Syntax to sort keys is

sort open bracket keys percentage hashName close bracket semicolon


Similarly, we can sort hash values as

sort open bracket values percentage hashName close bracket semicolon

Let us understand sorting functionality using a sample program.
Let me switch to sortHash dot pl on gedit.


Type the code as displayed on the screen in your sortHash dot pl file.

#!//usr/bin/perl


%addressHash = (

'City' => 'Pune',

'State' => 'Maharashtra',

'Country' => 'India'

);


foreach $key (sort(keys %addressHash)) {

print "Key: ", $key, " ==> ", $addressHash{$key}, "\n";

}


foreach $value (sort(values %addressHash)) {

print "Value: $value\n";

}

Here we have declared hash of address.


Here, to sort the keys we have used the sort inbuilt function, along with the keys function.


This will sort the hash keys in alphabetical order.







Similarly, we can use the sort function on values of hash.


Sorting can also be done on numeric keys and/or values.

Save the file and switch to terminal.
Terminal

perl sortHash.pl

Execute the script by typing

perl sortHash dot pl

Highlight the output The output will be as shown on the terminal.
Now, let us see how to get all keys and values of hash.
Slide Perl provides inbuilt function to fetch all the hash keys and values.
  • keys function is used to retrive all the keys of hash
  • values function returns values of all the keys whereas
  • each function iterates over hash and returns key/value pair from hash
Gedit Let us understand these functions using a sample program.


For this, we'll use perlHash dot pl script, which we have created earlier in this tutorial.

Gedit


#!/usr/bin/perl


%hash = (

'Name' => 'John',

'Department' => 'Finance'

);


print "Value of Key Name is: ", $hash{'Name'}, "\n";


@keysOfHash = keys(%hash);

print "Keys of a Hash are: @keysOfHash\n";


@valuesOfHash = values(%hash);

print "Values of a Hash are: @valuesOfHash\n";


while (($key, $value) = each(%hash)) {

print "key: $key and value: $value\n";

}

Type the following piece of code as shown on the screen;


<<pause>>











Highlight comma in print statement


@keysOfHash = keys(%hash);


@valuesOfHash = values(%hash);

Let us understand the code now.


keys function on hash, returns an array which contains all keys of hash.


values function on hash returns an array of values for all keys of hash.


each function returns the key/value pair.


Here, we have used the while loop.


It will iterate over each key/value pair of hash, that is returned by each function.

Press Ctrl+S to save the file.
Terminal

perl perlHash.pl


Now, let us execute the script on the terminal by typing

perl perlHash dot pl

Press Enter

Highlight the output. The following output will be seen on the terminal.
Now let us see few other ways of looping over hash.
Slide


foreach $variable (keys(%hashName)) {

# Action to be performed

}

We can use foreach loop to iterate over each key of hash.


Then perform a set of actions on the value of a key.

On the Slide, point to each of the words as per the narration.


The syntax is as displayed on the screen.


Here, each iteration of foreach loop will assign key from hash to $variable.


Then it will use that $variable to fetch the value or to perform a set of actions.

foreach $variable (values(%hashName)) {

# Action to be performed

}

Similarly, we can loop over hash values as shown on the screen.
Gedit We will look at a sample program.


So, let me switch to loopingOverHash dot pl in gedit.

#!/usr/bin/perl


%hash = (

'Name' => 'John',

'Department' => 'Finance'

);


foreach $key (keys(%hash)) {

print "Key is $key and it's value is $hash{$key}\n";

}


print "==================

====================\n";


foreach $value (values(%hash)) {

print "Value is $value\n";

}

Type the following piece of code as shown in your loopingOverHash dot pl


<<pause>>

Highlight


foreach $key (keys(%hash))


This piece of code returns single key of hash.


Here in our case,

1st time dollar key ($key) contains the Department as key.


In the next iteration of foreach, Name key is returned.

Switch back to the slides Note: Hash is an unordered collection of data.

So, keys returned will not be in the sequence defined at the time of creating hash.

Back to gedit

foreach $value (values(%hash))

The loop on values works in a similar way.
Press ctrl + s Press Ctrl + S to save the file.
Switch to terminal


perl loopingOverHash.pl


Then, switch to terminal and execute the Perl script as

perl loopingOverHash dot pl


and press Enter.

Highlight the output on the terminal The following output is displayed on the terminal.

<pause>

Slide: Summary Let us summarize.

In this tutorial, we learnt -

  • Hash in Perl and
  • Accessing elements of a hash
  • using sample programs.
Slide: Assignment Here is assignment for you -
  1. Declare hash having student name as key
  2. And his/her percentage as the value.
  3. Loop over hash using keys, values and each function
  4. Then print the percentage of each student.
About the Project Watch the video available at the following link


It summaries the Spoken Tutorial project


If you do not have good bandwidth, you can

download and watch it

Spoken Tutorial Workshops The Spoken Tutorial Project Team


Conducts workshops using spoken tutorials


Gives certificates to those who pass an online

test


For more details, please write to

contact at spoken hyphen tutorial dot org

Acknowledgment


http://spoken-tutorial.org\NMEICT-Intro

Spoken Tutorial Project is a part of the Talk to a

Teacher project


It is supported by the National Mission on

Education through ICT, MHRD, Government of India.


More information on this Mission is available

spoken hypen tutorial dot org slash NMEICT hyphen Intro

Hope you enjoyed this Perl tutorial.

This is Amol Brahmankar signing off.


Thanks for joining

Contributors and Content Editors

AmolBrahmankar, Nancyvarkey