473,721 Members | 2,220 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Improve my Simple Code

24 New Member
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

Expand|Select|Wrap|Line Numbers
  1. #! /usr/bin/perl
  2. #Store your important phone numbers in a hash
  3. #Write a program to look up numbers by the persons name
  4.  
  5. use warnings;
  6. use strict;
  7. my $name;
  8. my $number;
  9. my %number = ( David => "999 999 9999", 
  10.                Tony => "111 111 1111",
  11.                Mike => "333 333 3333",
  12.                Mary=> "333 234 3433");
  13. print("Enter The Name You Are Looking For \n");
  14. $name = <STDIN>;
  15. chop($name);
  16. if ($name eq "David")
  17. {
  18. print ( $name, "'s number is: ", $number{$name}, "\n");
  19. }
  20.     elsif($name eq "Tony")
  21.     {
  22.     print ( $name, "'s number is: ", $number{$name}, "\n");
  23.     }
  24.         elsif($name eq "Mike")
  25.         {
  26.         print ( $name, "'s number is: ", $number{$name}, "\n");
  27.         }
  28.             elsif($name eq "Mary")
  29.             {
  30.             print ( $name, "'s number is: ", $number{$name}, "\n");
  31.             }
  32.                 else 
  33.                 {
  34.                 print ("Error: Name Not on List\n");
  35.                 }
Dec 25 '07 #1
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:
Expand|Select|Wrap|Line Numbers
  1. john:9198524578
  2. sally:9198524587
  3. jim:3048597562
  4. jessica:8682548759
  5.  
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.

Expand|Select|Wrap|Line Numbers
  1. #!/usr/bin/perl -T
  2.  
  3. use strict;
  4. use warnings;
  5.  
  6. use Tie::File;
  7.  
  8. my $result = "\n\nName not found";
  9.  
  10. tie my @phoneBook, 'Tie::File', "phoneBook.txt" or die "Can't open file: $!";
  11.  
  12.  
  13. print "Enter the name you are looking for";
  14.  
  15. chomp(my $name = <STDIN>);
  16. $name = lc($name); # convert to lowercase to ease search.
  17.  
  18. for my $e (@phoneBook){
  19.     if($e =~ /$name/){
  20.         my ($person, $number) = split(/:/, $e);
  21.         $result = "\n\n".ucfirst($person)."'s number is: ".$number;
  22.         }
  23. }
  24.  
  25. print $result;
  26.  
  27. untie @phoneBook;
  28.  
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!
Dec 25 '07 #2
autodidact
24 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:
Expand|Select|Wrap|Line Numbers
  1. john:9198524578
  2. sally:9198524587
  3. jim:3048597562
  4. jessica:8682548759
  5.  
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.

Expand|Select|Wrap|Line Numbers
  1. #!/usr/bin/perl -T
  2.  
  3. use strict;
  4. use warnings;
  5.  
  6. use Tie::File;
  7.  
  8. my $result = "\n\nName not found";
  9.  
  10. tie my @phoneBook, 'Tie::File', "phoneBook.txt" or die "Can't open file: $!";
  11.  
  12.  
  13. print "Enter the name you are looking for";
  14.  
  15. chomp(my $name = <STDIN>);
  16. $name = lc($name); # convert to lowercase to ease search.
  17.  
  18. for my $e (@phoneBook){
  19.     if($e =~ /$name/){
  20.         my ($person, $number) = split(/:/, $e);
  21.         $result = "\n\n".ucfirst($person)."'s number is: ".$number;
  22.         }
  23. }
  24.  
  25. print $result;
  26.  
  27. untie @phoneBook;
  28.  
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.
Dec 25 '07 #3
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

Expand|Select|Wrap|Line Numbers
  1. #! /usr/bin/perl
  2. #Store your important phone numbers in a hash
  3. #Write a program to look up numbers by the persons name
  4.  
  5. use warnings;
  6. use strict;
  7. my $name;
  8. my $number;
  9. my %number = ( David => "999 999 9999", 
  10.                Tony => "111 111 1111",
  11.                Mike => "333 333 3333",
  12.                Mary=> "333 234 3433");
  13. print("Enter The Name You Are Looking For \n");
  14. $name = <STDIN>;
  15. chop($name);
  16. if ($name eq "David")
  17. {
  18. print ( $name, "'s number is: ", $number{$name}, "\n");
  19. }
  20.     elsif($name eq "Tony")
  21.     {
  22.     print ( $name, "'s number is: ", $number{$name}, "\n");
  23.     }
  24.         elsif($name eq "Mike")
  25.         {
  26.         print ( $name, "'s number is: ", $number{$name}, "\n");
  27.         }
  28.             elsif($name eq "Mary")
  29.             {
  30.             print ( $name, "'s number is: ", $number{$name}, "\n");
  31.             }
  32.                 else 
  33.                 {
  34.                 print ("Error: Name Not on List\n");
  35.                 }

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:

Expand|Select|Wrap|Line Numbers
  1. #! /usr/bin/perl
  2. #Store your important phone numbers in a hash
  3. #Write a program to look up numbers by the persons name
  4.  
  5. use warnings;
  6. use strict;
  7.  
  8. my %number = ( David => "999 999 9999", 
  9.                Tony => "111 111 1111",
  10.                Mike => "333 333 3333",
  11.                Mary=> "333 234 3433");
  12. print("Enter The Name You Are Looking For: ");
  13. chomp(my $name = <STDIN>);
  14. 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:

Expand|Select|Wrap|Line Numbers
  1. #! /usr/bin/perl
  2. #Store your important phone numbers in a hash
  3. #Write a program to look up numbers by the persons name
  4.  
  5. use warnings;
  6. use strict;
  7.  
  8. my %number = ( David => "999 999 9999", 
  9.                Tony => "111 111 1111",
  10.                Mike => "333 333 3333",
  11.                Mary=> "333 234 3433");
  12. print("Enter The Name You Are Looking For: ");
  13.  
  14. chomp(my $name = <STDIN>);
  15. error($name) if (!exists $number{$name});
  16. print "${name}'s number is: $number{$name}\n";
  17.  
  18.  
  19. sub error {
  20.     my $what = shift;
  21.     # some code here to handle errors
  22.     exit;
  23. }     
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".
Dec 25 '07 #4
autodidact
24 New Member
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:

Expand|Select|Wrap|Line Numbers
  1. #! /usr/bin/perl
  2. #Store your important phone numbers in a hash
  3. #Write a program to look up numbers by the persons name
  4.  
  5. use warnings;
  6. use strict;
  7.  
  8. my %number = ( David => "999 999 9999", 
  9.                Tony => "111 111 1111",
  10.                Mike => "333 333 3333",
  11.                Mary=> "333 234 3433");
  12. print("Enter The Name You Are Looking For: ");
  13. chomp(my $name = <STDIN>);
  14. 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:

Expand|Select|Wrap|Line Numbers
  1. #! /usr/bin/perl
  2. #Store your important phone numbers in a hash
  3. #Write a program to look up numbers by the persons name
  4.  
  5. use warnings;
  6. use strict;
  7.  
  8. my %number = ( David => "999 999 9999", 
  9.                Tony => "111 111 1111",
  10.                Mike => "333 333 3333",
  11.                Mary=> "333 234 3433");
  12. print("Enter The Name You Are Looking For: ");
  13.  
  14. chomp(my $name = <STDIN>);
  15. error($name) if (!exists $number{$name});
  16. print "${name}'s number is: $number{$name}\n";
  17.  
  18.  
  19. sub error {
  20.     my $what = shift;
  21.     # some code here to handle errors
  22.     exit;
  23. }     
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.
Dec 26 '07 #5
autodidact
24 New Member

Expand|Select|Wrap|Line Numbers
  1. #! /usr/bin/perl
  2. #Store your important phone numbers in a hash
  3. #Write a program to look up numbers by the persons name
  4.  
  5. use warnings;
  6. use strict;
  7.  
  8. my %number = ( David => "999 999 9999", 
  9.                Tony => "111 111 1111",
  10.                Mike => "333 333 3333",
  11.                Mary=> "333 234 3433");
  12. print("Enter The Name You Are Looking For: ");
  13.  
  14. chomp(my $name = <STDIN>);
  15. error($name) if (!exists $number{$name});
  16. print "${name}'s number is: $number{$name}\n";
  17.  
  18.  
  19. sub error {
  20.     my $what = shift;
  21.     # some code here to handle errors
  22.     exit;
  23. }     
Thanks KevinADC,
I don't seem to understand what the command below is doing
Expand|Select|Wrap|Line Numbers
  1. my $what = shift;  
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?
Dec 30 '07 #6
numberwhun
3,509 Recognized Expert Moderator Specialist
Thanks KevinADC,
I don't seem to understand what the command below is doing
Expand|Select|Wrap|Line Numbers
  1. my $what = shift;  
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
Dec 30 '07 #7
KevinADC
4,059 Recognized Expert Specialist
Thanks KevinADC,
I don't seem to understand what the command below is doing
Expand|Select|Wrap|Line Numbers
  1. my $what = shift;  
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.
Dec 30 '07 #8
autodidact
24 New Member
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!
Jan 1 '08 #9

Sign in to post your reply or Sign up for a free account.

Similar topics

65
12591
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:
17
1173
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
41
2525
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...
7
1584
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;
11
2652
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.
16
3069
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.
11
3383
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.
2
2770
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...
4
1327
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
0
8840
marktang
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...
0
8730
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,...
0
9367
Oralloy
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...
0
9215
jinu1996
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...
1
6669
isladogs
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...
0
5981
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();...
0
4753
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3189
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
2
2576
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.