Improve my Simple Code

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • autodidact
    New Member
    • Sep 2007
    • 24

    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

    [CODE=perl]#! /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");
    }[/CODE]
    Last edited by eWish; Dec 25 '07, 12:47 PM. Reason: Added Code Tags
  • Kelicula
    Recognized Expert New Member
    • Jul 2007
    • 176

    #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:
    [code=text]
    john:9198524578
    sally:919852458 7
    jim:3048597562
    jessica:8682548 759
    [/code]

    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.

    [code=perl]
    #!/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;
    [/code]

    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!

    Comment

    • autodidact
      New Member
      • Sep 2007
      • 24

      #3
      Originally posted by Kelicula
      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:
      [code=text]
      john:9198524578
      sally:919852458 7
      jim:3048597562
      jessica:8682548 759
      [/code]

      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.

      [code=perl]
      #!/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;
      [/code]

      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.

      Comment

      • KevinADC
        Recognized Expert Specialist
        • Jan 2007
        • 4092

        #4
        Originally posted by autodidact
        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

        [CODE=perl]#! /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");
        }[/CODE]

        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:

        [CODE=perl]#! /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";[/CODE]

        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:

        [CODE=perl]#! /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;
        } [/CODE]

        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".

        Comment

        • autodidact
          New Member
          • Sep 2007
          • 24

          #5
          Originally posted by KevinADC
          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:

          [CODE=perl]#! /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";[/CODE]

          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:

          [CODE=perl]#! /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;
          } [/CODE]

          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.

          Comment

          • autodidact
            New Member
            • Sep 2007
            • 24

            #6
            Originally posted by KevinADC

            [CODE=perl]#! /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;
            } [/CODE]
            Thanks KevinADC,
            I don't seem to understand what the command below is doing [CODE=perl]my $what = shift; [/CODE]

            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?

            Originally posted by KevinADC

            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?

            Comment

            • numberwhun
              Recognized Expert Moderator Specialist
              • May 2007
              • 3467

              #7
              Originally posted by autodidact
              Thanks KevinADC,
              I don't seem to understand what the command below is doing [CODE=perl]my $what = shift; [/CODE]
              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.


              Originally posted by autodidact
              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.

              Originally posted by autodidact
              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

              Comment

              • KevinADC
                Recognized Expert Specialist
                • Jan 2007
                • 4092

                #8
                Originally posted by autodidact
                Thanks KevinADC,
                I don't seem to understand what the command below is doing [CODE=perl]my $what = shift; [/CODE]

                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.

                Comment

                • autodidact
                  New Member
                  • Sep 2007
                  • 24

                  #9
                  Originally posted by KevinADC
                  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!

                  Comment

                  Working...