473,325 Members | 2,771 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,325 software developers and data experts.

Improve my Simple Code

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 1808
Kelicula
176 Expert 100+
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
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 Expert 2GB
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
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

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 Expert Mod 2GB
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 Expert 2GB
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
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
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...
17
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
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...
7
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,...
11
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...
16
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...
11
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...
2
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...
4
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
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...

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.