In: Computer Science
In Perl:
Key1, value1
Key2, value2
…, …
(Please if you can, provide screenshots)
Thank YOU!
The Perl source code along with the relevant comments is given below.
#!/usr/bin/perl
#create and initialize a dictionary called dict containing five
elements
%dict = ('Jean Paul', 55,
'Lloyd', 32,
'Khan', 40,
'Woodie',
26,
'James',
18);
@name = keys %dict; #name is now an array
of all the keys in the dictionary dict
@age = values %dict; #age is now an array of all
the values in the dictionary dict
print "Accessing values using keys:-\n";
#accessing value using keys
print "$name[0]\n";
print "$name[1]\n";
print "$name[2]\n\n";
print "Accessing values using value:-\n";
#accessing value using values
print "$age[0]\n";
print "$age[1]\n";
print "$age[2]\n\n";
print "Adding a new key-value pair:-\n";
#adding a new key value pair to the dictionary dict
$dict{'Albert'} = 65;
print "\$dict{'Albert'} = $dict{'Albert'}\n\n";
print "Update an existing key-value pair:-\n";
#updating an existing pair using assignment
$dict{'James'} = 30;
print "\$dict{'James'} = $dict{'James'}\n\n";
print "Delete a key-value pair:-\n\n";
#delete a key value pair
delete $dict{'Lloyd'};
print "Checking for key existence:-\n";
#check if a key exists in the dictionary
if(exists($dict{'Lloyd'}))
{ print "\$dict{'Lloyd'} value found\n";}
else
{ print "\$dict{'Lloyd'} - no records found\n";}
if(exists($dict{'Khan'}))
{ print "\$dict{'Khan'} value found\n";}
else
{ print "No records found\n";}
if(exists($dict{'Albert'}))
{ print "\$dict{'Albert'} value found\n\n";}
else
{ print "No records found\n\n";}
print "Iterating the dictionary using while loop:-\n";
#iterating dictionary using while loop
while(my($k, $v) = each %dict)
{ print "$k, $v\n"
}
If the indendation are not clear, please refer the screenshot of the code given below.
The screenshot of the output is also given below.
Explanation
Hope this helps. Doubts, if any, can be asked in the comment section.