In: Computer Science
WRITE IN PERL
Creating a Perl Product Directory - A product "id" will be used to identify a product (the key) and the description will be stored as the value
Here is a template:
#!/usr/bin/perl
use warnings;
%products = (); # empty hash to store products in
sub getChoice(){
print("Welcome to the Product Directory\n");
print("1. Add a Product to Directory\n");
print("2. Remove a Product from Director\n");
print("3. Lookup a Product in Directory\n");
print("4. List all products\n");
print("5. Quit\n");
print("Enter your option: ")
chomp($choice = <STDIN>);
return $choice
}
$c = getChoice();
while($c ne "5"){
if($c eq "1"){
# Ask the user to enter input for a product's ID
# Ask the user to enter input for a product's description
# Add the item to the hash with the supplied ID as the key and
description as the value
}
# Options 2 - 4
}
Please find the below program. Also attaching the screenshot of sample output.
Please provide your feedback
Thanks and Happy Learning!
Sample output:
#!/usr/bin/perl
use warnings;
%products = (); # empty hash to store products in
sub getChoice()
{
print("Welcome to the Product Directory\n");
print("1. Add a Product to Directory\n");
print("2. Remove a Product from Directory\n");
print("3. Lookup a Product in Directory\n");
print("4. List all products\n");
print("5. Quit\n");
print("Enter your option: ");
chomp($choice = <STDIN>);
return $choice
}
$c = getChoice();
while($c ne "5")
{
if($c eq "1")
{
# Ask the user to enter input for a product's ID
print("Enter the product ID: ");
chomp($productId = <STDIN>);
# Ask the user to enter input for a product's description
print("Enter the product description: ");
chomp($productDesc = <STDIN>);
# Add the item to the hash with the supplied ID as the key and description as the value
$products{$productId} = $productDesc;
}
elsif($c eq "2")
{
# Ask the user to enter input for a product's ID
print("Enter the product ID: ");
chomp($productId = <STDIN>);
# If the ID exists in the hash, that entry is deleted from the hash
if (exists($products{$productId}))
{
delete($products{$productId});
}
}
elsif($c eq "3")
{
# Ask the user to enter input for a product's ID
print("Enter the product ID: ");
chomp($productId = <STDIN>);
# If the ID exists in the hash, that entry's value is printed (the description)
if (exists($products{$productId}))
{
print("$products{$productId}\n");
}
}
elsif($c eq "4")
{
#Prints all the key/value pairs of the hash, each entry on a new line with with
#a colon or dash separating the ID from the description
while (($key, $value) = each (%products))
{
print "$key:$value\n";
}
}
$c = getChoice();
}