I wrote a simple code to look up peoples numbers.
But what if the user types in a name that is not on the list, how may i get my code to alert the user try again till a correct name is entered?
I'm trying to kill two birds with one stone. So how would you guys rate my code in terms of efficiency. And any additional comments would be appreciated.
Thanks In Advance!
My code also be viewed here - #! /usr/bin/perl
-
#Store your important phone numbers in a hash
-
#Write a program to look up numbers by the persons name
-
-
use warnings;
-
use strict;
-
my $name;
-
my $number;
-
my %number = ( David => "999 999 9999",
-
Tony => "111 111 1111",
-
Mike => "333 333 3333",
-
Mary=> "333 234 3433");
-
print("Enter The Name You Are Looking For \n");
-
$name = <STDIN>;
-
chop($name);
-
if ($name eq "David")
-
{
-
print ( $name, "'s number is: ", $number{$name}, "\n");
-
}
-
elsif($name eq "Tony")
-
{
-
print ( $name, "'s number is: ", $number{$name}, "\n");
-
}
-
elsif($name eq "Mike")
-
{
-
print ( $name, "'s number is: ", $number{$name}, "\n");
-
}
-
elsif($name eq "Mary")
-
{
-
print ( $name, "'s number is: ", $number{$name}, "\n");
-
}
-
else
-
{
-
print ("Error: Name Not on List\n");
-
}
8 1833 Kelicula 176
Recognized Expert New Member
Here's how I would do it.
First I am assuming that the list of numbers could get large, so put them in a separate file. Call it "phoneBook. txt" keep it in the same directory.
In it list the persons name followed by their number separated (or delimited would be a better word) with colons ":" followed by a line break.
eg: -
john:9198524578
-
sally:9198524587
-
jim:3048597562
-
jessica:8682548759
-
Use Tie::File to access it, (saving lots of temporary memory).
Then simply scan it for the name.
Display the result, which defaults to Not found.
If it is found though the info will be stored in the result variable.
Not sure if it is the BEST way to do it, but it's not much code, and it runs quick.
Also I noticed you are not altering the phoneBook file, but if you ever did you would want to use Fcntl to lock the file.
Here ya go, fully tested and usable code. -
#!/usr/bin/perl -T
-
-
use strict;
-
use warnings;
-
-
use Tie::File;
-
-
my $result = "\n\nName not found";
-
-
tie my @phoneBook, 'Tie::File', "phoneBook.txt" or die "Can't open file: $!";
-
-
-
print "Enter the name you are looking for";
-
-
chomp(my $name = <STDIN>);
-
$name = lc($name); # convert to lowercase to ease search.
-
-
for my $e (@phoneBook){
-
if($e =~ /$name/){
-
my ($person, $number) = split(/:/, $e);
-
$result = "\n\n".ucfirst($person)."'s number is: ".$number;
-
}
-
}
-
-
print $result;
-
-
untie @phoneBook;
-
This way you don't have to include every one of the names in the code.
if, else, even switch would not eliminate having to write out each and every name that could be entered.
Good luck!
Here's how I would do it.
First I am assuming that the list of numbers could get large, so put them in a separate file. Call it "phoneBook. txt" keep it in the same directory.
In it list the persons name followed by their number separated (or delimited would be a better word) with colons ":" followed by a line break.
eg: -
john:9198524578
-
sally:9198524587
-
jim:3048597562
-
jessica:8682548759
-
Use Tie::File to access it, (saving lots of temporary memory).
Then simply scan it for the name.
Display the result, which defaults to Not found.
If it is found though the info will be stored in the result variable.
Not sure if it is the BEST way to do it, but it's not much code, and it runs quick.
Also I noticed you are not altering the phoneBook file, but if you ever did you would want to use Fcntl to lock the file.
Here ya go, fully tested and usable code. -
#!/usr/bin/perl -T
-
-
use strict;
-
use warnings;
-
-
use Tie::File;
-
-
my $result = "\n\nName not found";
-
-
tie my @phoneBook, 'Tie::File', "phoneBook.txt" or die "Can't open file: $!";
-
-
-
print "Enter the name you are looking for";
-
-
chomp(my $name = <STDIN>);
-
$name = lc($name); # convert to lowercase to ease search.
-
-
for my $e (@phoneBook){
-
if($e =~ /$name/){
-
my ($person, $number) = split(/:/, $e);
-
$result = "\n\n".ucfirst($person)."'s number is: ".$number;
-
}
-
}
-
-
print $result;
-
-
untie @phoneBook;
-
This way you don't have to include every one of the names in the code.
if, else, even switch would not eliminate having to write out each and every name that could be entered.
Good luck!
Thank You Kelicula, I'm not an expert, but I'll definitely give your method a shot and I'll try and understand it too. Introducing me to new commands should hasten my learning process.
KevinADC 4,059
Recognized Expert Specialist
I wrote a simple code to look up peoples numbers.
But what if the user types in a name that is not on the list, how may i get my code to alert the user try again till a correct name is entered?
I'm trying to kill two birds with one stone. So how would you guys rate my code in terms of efficiency. And any additional comments would be appreciated.
Thanks In Advance!
My code also be viewed here - #! /usr/bin/perl
-
#Store your important phone numbers in a hash
-
#Write a program to look up numbers by the persons name
-
-
use warnings;
-
use strict;
-
my $name;
-
my $number;
-
my %number = ( David => "999 999 9999",
-
Tony => "111 111 1111",
-
Mike => "333 333 3333",
-
Mary=> "333 234 3433");
-
print("Enter The Name You Are Looking For \n");
-
$name = <STDIN>;
-
chop($name);
-
if ($name eq "David")
-
{
-
print ( $name, "'s number is: ", $number{$name}, "\n");
-
}
-
elsif($name eq "Tony")
-
{
-
print ( $name, "'s number is: ", $number{$name}, "\n");
-
}
-
elsif($name eq "Mike")
-
{
-
print ( $name, "'s number is: ", $number{$name}, "\n");
-
}
-
elsif($name eq "Mary")
-
{
-
print ( $name, "'s number is: ", $number{$name}, "\n");
-
}
-
else
-
{
-
print ("Error: Name Not on List\n");
-
}
This is not the way I would do it in a real working script, but for just the code/assignment you posted I would do this: - #! /usr/bin/perl
-
#Store your important phone numbers in a hash
-
#Write a program to look up numbers by the persons name
-
-
use warnings;
-
use strict;
-
-
my %number = ( David => "999 999 9999",
-
Tony => "111 111 1111",
-
Mike => "333 333 3333",
-
Mary=> "333 234 3433");
-
print("Enter The Name You Are Looking For: ");
-
chomp(my $name = <STDIN>);
-
print exists $number{$name} ? "${name}'s number is: $number{$name}\n" : "Error: Name [$name] Not on List\n";
In a real program I would use a subroutine to handle all errors instead of the simple warning that is printed to alert the user about what happened. Something like: - #! /usr/bin/perl
-
#Store your important phone numbers in a hash
-
#Write a program to look up numbers by the persons name
-
-
use warnings;
-
use strict;
-
-
my %number = ( David => "999 999 9999",
-
Tony => "111 111 1111",
-
Mike => "333 333 3333",
-
Mary=> "333 234 3433");
-
print("Enter The Name You Are Looking For: ");
-
-
chomp(my $name = <STDIN>);
-
error($name) if (!exists $number{$name});
-
print "${name}'s number is: $number{$name}\n";
-
-
-
sub error {
-
my $what = shift;
-
# some code here to handle errors
-
exit;
-
}
Your code looks like something a beginner to perl would write. It is much too verbose (too much code) for such a simple task. But for a beginner it is not bad, and points for using "strict" and "warnings".
This is not the way I would do it in a real working script, but for just the code/assignment you posted I would do this: - #! /usr/bin/perl
-
#Store your important phone numbers in a hash
-
#Write a program to look up numbers by the persons name
-
-
use warnings;
-
use strict;
-
-
my %number = ( David => "999 999 9999",
-
Tony => "111 111 1111",
-
Mike => "333 333 3333",
-
Mary=> "333 234 3433");
-
print("Enter The Name You Are Looking For: ");
-
chomp(my $name = <STDIN>);
-
print exists $number{$name} ? "${name}'s number is: $number{$name}\n" : "Error: Name [$name] Not on List\n";
In a real program I would use a subroutine to handle all errors instead of the simple warning that is printed to alert the user about what happened. Something like: - #! /usr/bin/perl
-
#Store your important phone numbers in a hash
-
#Write a program to look up numbers by the persons name
-
-
use warnings;
-
use strict;
-
-
my %number = ( David => "999 999 9999",
-
Tony => "111 111 1111",
-
Mike => "333 333 3333",
-
Mary=> "333 234 3433");
-
print("Enter The Name You Are Looking For: ");
-
-
chomp(my $name = <STDIN>);
-
error($name) if (!exists $number{$name});
-
print "${name}'s number is: $number{$name}\n";
-
-
-
sub error {
-
my $what = shift;
-
# some code here to handle errors
-
exit;
-
}
Your code looks like something a beginner to perl would write. It is much too verbose (too much code) for such a simple task. But for a beginner it is not bad, and points for using "strict" and "warnings".
Thanks! ADC for your input. I'll work on everything. I hope to grasp this all soon.
- #! /usr/bin/perl
-
#Store your important phone numbers in a hash
-
#Write a program to look up numbers by the persons name
-
-
use warnings;
-
use strict;
-
-
my %number = ( David => "999 999 9999",
-
Tony => "111 111 1111",
-
Mike => "333 333 3333",
-
Mary=> "333 234 3433");
-
print("Enter The Name You Are Looking For: ");
-
-
chomp(my $name = <STDIN>);
-
error($name) if (!exists $number{$name});
-
print "${name}'s number is: $number{$name}\n";
-
-
-
sub error {
-
my $what = shift;
-
# some code here to handle errors
-
exit;
-
}
Thanks KevinADC,
I don't seem to understand what the command below is doing
It seems to me, that the sub error is automatically called when error is true. What if i wanted to check for another error with its own sub error, How would i be able to distinguish one from the other?
This is not the way I would do it in a real working script, but for just the code/assignment you posted I would do this
In a real program I would use a subroutine to handle all errors instead of the simple warning that is printed to alert the user about what happened. Something like:
How do i learn how to write real working scripts as i learn how to program.?
On a side note, as i learn Perl (for myself) i find it hard grasping certain concepts. I usually skip them and move on to the next subsection/section, with hopes of coming back to it. Is this a good thing?
numberwhun 3,509
Recognized Expert Moderator Specialist
Thanks KevinADC,
I don't seem to understand what the command below is doing
If you look at the error function, it takes an argument. Perl has a lot of shortcuts , and if you don't know what they are, it can be rather confusing.
The shortcut that Kevin used basically takes and removes the first (and only) element in the array holding the arguments to the function call.
It seems to me, that the sub error is automatically called when error is true. What if i wanted to check for another error with its own sub error, How would i be able to distinguish one from the other?
If you look, Kevin calls the "error()" function if statement is true. So, you could write another function that could be called in the instance of another test being true/false.
How do i learn how to write real working scripts as i learn how to program.?
On a side note, as i learn Perl (for myself) i find it hard grasping certain concepts. I usually skip them and move on to the next subsection/section, with hopes of coming back to it. Is this a good thing?
Check your PM's. I have PM'd you off of this thread regarding learning Perl. (your PM's are at the top of the screen under the "PMs" link. It should have a number next to it as well, indicating how many new PMs you have).
As far as concepts go, if you are following a book or tutorial, they are usually laid out so that what they teach is taught before it is used heavily (generally). So, if you don't understand a concept, then you NEED to concentrate on it and learn it. The best way to do that is to post your questions here regarding what you don't understand and see if either of the Kevin's (KevinADC or eWish) or myself can give a more layman's explanation and try to get you to understand it.
Regards and Happy Holidays!
Jeff
KevinADC 4,059
Recognized Expert Specialist
Thanks KevinADC,
I don't seem to understand what the command below is doing
It seems to me, that the sub error is automatically called when error is true. What if i wanted to check for another error with its own sub error, How would i be able to distinguish one from the other?
How do i learn how to write real working scripts as i learn how to program.?
On a side note, as i learn Perl (for myself) i find it hard grasping certain concepts. I usually skip them and move on to the next subsection/section, with hopes of coming back to it. Is this a good thing?
You don't really want to have seperate error subroutines unless the errors are of a totally different nature. Instead you write a generic error routine and send arguments to it and use those arguments as messages or instructions so the error sub knows what to do. You might be too early in your perl education to grasp that entirely.
As far as learning and writing programs... most perl coders are self taught, myself included. I did just what you are doing, I learned to do something on a need to know basis which means I jumped around a whole lot and wrote some pretty bad code and left some large gaps in my perl education.
Forums are a great resource. You will learn how to write good code from people on forums, using the best and most efficient methods. You will also get a lot of mediocre and some just plain bad suggestions from people who want to help but have limited experience.
You don't really want to have seperate error subroutines unless the errors are of a totally different nature. Instead you write a generic error routine and send arguments to it and use those arguments as messages or instructions so the error sub knows what to do. You might be too early in your perl education to grasp that entirely.
As far as learning and writing programs... most perl coders are self taught, myself included. I did just what you are doing, I learned to do something on a need to know basis which means I jumped around a whole lot and wrote some pretty bad code and left some large gaps in my perl education.
Forums are a great resource. You will learn how to write good code from people on forums, using the best and most efficient methods. You will also get a lot of mediocre and some just plain bad suggestions from people who want to help but have limited experience.
Thanks for your advice KevinADC. You guys are great!
Sign in to post your reply or Sign up for a free account.
Similar topics |
by: Skybuck Flying |
last post by:
Hi,
I needed a method to determine if a point was on a line segment in 2D. So I
googled for some help and so far I have evaluated two methods.
The first method was only a formula, the second method was a piece of C code
which turned out to be incorrect and incomplete but by modifieing it would
still be usuable.
The first method was this piece of text:
|
by: py |
last post by:
Say I have...
x = "132.00"
but I'd like to display it to be "132" ...dropping the trailing
zeros...I currently try this
if x.endswith("0"):
x = x
if x.endswith("0"):
x = x
|
by: Petr Jakes |
last post by:
Hello,
I am trying to study/understand OOP principles using Python. I have
found following code http://tinyurl.com/a4zkn about FSM (finite state
machine) on this list, which looks quite useful for my purposes. As
this code was posted long time ago (November 1998) I would like to ask
if the principles used in this code are still valid in the "modern"
Python and if/how it can be improved (revrited) using futures of
current version of...
|
by: dphizler |
last post by:
This is the basic concept of my code:
#include <iostream.h>
#include <math.h>
#include <stdlib.h>
int main() {
double Gtotal, L, size, distance, theRandom;
double Gi;
int xi, xf, yi, yf, zi, zf;
|
by: Paul H |
last post by:
Suppose I have a table called tblPeople and I want a field to illustrate
whether each person prefers cats or dogs. I could do it one of three ways.
1. A plain text field
Create a text field in tblPeople called PreferredPet.
2. A lookup field that stores text values.
Create a text field in tblPeople called PreferredPetID and use it to lookup
an identical text field in tblPreferredPets.
| |
by: weidongtom |
last post by:
Hi,
I have just finished reading some tutorials on C, I am wondering how I
could improve my skill. Is there any advice? Is reading others' codes
the best way? If so, what type of codes are suitable for novice? The
ones in fsf freed software directory? I have been reading quite a few
books on the programming language C, but when I tried to start a
project of my own, I find myself to be incompetent. What should I do?
Thanks in advance.
|
by: Peted |
last post by:
Im using c# 2005 express edition
Ive pretty much finished an winforms application and i need to
significantly improve the visual appeal of the interface.
Im totaly stuck on this and cant seem to work out how to start on a
solution.
I have of course used a varienty of componets, mostly radio buttons
with "button" appearence.
|
by: sdanda |
last post by:
Hi ,
Do you have any idea how to improve my java class performance while selecting and inserting data into DB using JDBC Connectivity .........
This has to work for more than 8,00,000 of records ..... Can you give some performance tips if you have known
1) For this I am using oci driver ( because I m using oracle 10g) instead of thin driver
2) In that programme I m using prepared statement instead of statement
3) I am...
|
by: mrajanikrishna |
last post by:
Hi friends,
I have a page which has dropdownlists bound to data source
controls. Its a big page has some input controls.
How can I improve the page rendering time/
thanks
|
by: marktang |
last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look !
Part I. Meaning of...
|
by: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it.
First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
| |
by: Oralloy |
last post by:
Hello folks,
I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>".
The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed.
This is as boiled down as I can make it.
Here is my compilation command:
g++-12 -std=c++20 -Wnarrowing bit_field.cpp
Here is the code in...
|
by: jinu1996 |
last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth.
The Art of Business Website Design
Your website is...
|
by: isladogs |
last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM).
In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules.
He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms.
Adolph will...
|
by: conductexam |
last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one.
At the time of converting from word file to html my equations which are in the word document file was convert into image.
Globals.ThisAddIn.Application.ActiveDocument.Select();...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
by: 6302768590 |
last post by:
Hai team
i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
| |
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |