In: Computer Science
Perl is a programming language that can be used on Linux.
Write a Perl shell script named phone.pl that prompts the user to enter first or last or any portion of person’s name, so that can be found the appropriate entry in the phone directory file called “phones”.
If the user tries to enter name as the argument on the command line, he/she will get a warning message “You need to provide name when prompted by this script!”
If the person’s entry does NOT exist in the file “phones” then it will be displayed the following message “Name NOT found in the phone directory file!” (where Name is the user’s input).
A text file list of names and information similar to the final output of sample run #2 has been provided by the teacher.
Sample Run #1:
INPUT: $ perl phone.pl Chad
OUTPUT: You need to provide name when prompted by this script!
Sample Run #2:
INPUT 1: $ perl phone.pl
OUTPUT 1: Enter a name to search for:
INPUT 2: Chad
OUTPUT 2: Brockman, Chad 920-213-0043 [email protected]
Sample Run #3:
INPUT 1: $ perl phone.pl
OUTPUT 1: Enter a name to search for:
INPUT 2: User
OUTPUT 2: User not found in the phone directory file
Here I have implemented Perl code as per your requirement, also I have attached the output of the code. Let me know in the comment section if have any query regarding the following code.
phone.pl
#!/usr/bin/perl
if($#ARGV!=-1)
{
# Argument on the command line
print("You need to provide name when prompted by this script!\n");
}
else
{
print("Enter a name to search for: ");
# take input
$name=<>;
chop($name);
# open phones file
open(DATA, "<phones") or die "Couldn't open file file.txt, $!";
# keep track of
# name found or not
$found=0;
# loop over whole file
while(<DATA>) {
# the line which is separated by
# space and store into an array
my @spl = split(' ', $_);
# Here we need to delete the last
# character because as per the given
# format the last character is ','
# So we have to remove the last character
chop(@spl[0]);
# first name(first argument)
$f_name=@spl[0];
# second name(second argument)
$l_name=@spl[1];
# Compare the name
if($f_name eq $name or $l_name eq $name)
{
$found=1;
print($_);
# the user found, So break the loop
last;
}
}
# if user not found
if($found==0)
{
print("User not found in the phone directory file\n");
}
close(DATA);
}
Output: