Loading ...
Sorry, an error occurred while loading the content.
 

Hash question

Expand Messages
  • ethelannrocks
    I have the following code that works, but I don t understand two things: 1. Why does the first line of the code have to be an empty hash? It works, but if
    Message 1 of 5 , Dec 1, 2008
      I have the following code that works, but I don't understand two things:

      1. Why does the first line of the code have to be an empty hash? It works, but if this is
      right, I don't understand why it needs to be where it is.
      Line 3 - %hash = ();

      2. I don't understand line 112, $name_found = 'N';
      once again, it works, but I don't even recall why I entered it there and why it is needed as
      it doesn't seem to tie in with the code that follows.

      If anyone can help me learn and understand these, I thank you!

      Here's the code:

      #!/usr/bin/perl

      #Create empty hash table.
      %hash = (); #MY FIRST QUESTION IS ABOUT THIS LINE AND WHY IT SHOULD BE HERE.


      ##Prompt a user for first name then last name.

      while(1)
      {
      print "\n";
      print "Notice, you may enter 'done' at any time to exit this loop.\n";
      print "If you enter the word 'exit' you will leave the entire program.\n\n";

      print "Enter a first name: ";
      chomp($firstname = <STDIN>);

      if ($firstname eq "done")
      {
      last;
      }

      if ($firstname eq "exit")
      {
      exit;
      }

      if ($firstname eq "")
      {
      print "You still need to enter your first name!\n";
      next;
      }

      print "Enter a last name: ";
      chomp($lastname = <STDIN>);

      if ($lastname eq "done")
      {
      last;
      }

      if ($lastname eq "exit")
      {
      exit;
      }

      if ($lastname eq "")
      {
      print "You still need to enter your last name!\n";
      next;
      }

      $name = ($lastname . ", " . $firstname);

      #000000000000000000000000000
      ## Prompt user to enter password.
      #000000000000000000000000000

      print "Please enter a combination of any letters and numbers for a password: ";
      chomp($password = <STDIN>);

      if ($password eq "done")
      {
      last;
      }

      if ($password eq "")
      {
      print "You still need to enter your password!\n";
      next;
      }

      if ($password eq "exit")
      {
      exit;
      }


      #Debug line below
      print "$name $password\n\n";

      #Load data into the hash table

      $hash{$name} = $password;
      print $hash{$name};
      print "\n";

      } #End of while(1)

      #000000000000000000000000000000000000000000000000000000000000000000

      #Prompt user to enter a last name and first name to search.
      #If found, display first name, last name, and pw.
      #If not found, say sorry and prompt to try again.

      @newarray = sort(keys(%hash));

      print "\n\n";
      while(1)
      {
      print "\n";
      print "Notice, you may enter 'exit' at any time to exit this loop.\n";
      print "Enter the last name, a comma, a space and then a first name to search.\n";
      print "For example: maines, natalie\n";
      chomp ($input_name = <STDIN>);

      if ($input_name eq "exit")
      {
      exit;
      }

      $name_found = 'N'; #MY 2ND QUESTION IS ABOUT THIS LINE AND WHY IT WORKS
      HERE.
      foreach $name (@newarray)
      {
      if ("$input_name" eq "$name")
      {
      print $name." has the password ".$hash{$name}."\n";
      $name_found = 'Y';
      last;
      }

      } #close foreach

      if ("$name_found" eq 'N')
      {
      print "Sorry, there is no such person found. Please try again. \n";
      }

      } #End of while(1)
    • Charles K. Clarkson
      ... I tried your code on my local machine and the program works fine with this line commented out. What led you to believe it wouldn t? ... $name_found is
      Message 2 of 5 , Dec 1, 2008
        ethelannrocks wrote:

        > I have the following code that works, but I don't understand two things:
        >
        > 1. Why does the first line of the code have to be an empty hash?

        I tried your code on my local machine and the program works fine
        with this line commented out. What led you to believe it wouldn't?


        > 2. I don't understand line 112, $name_found = 'N';
        > once again, it works, but I don't even recall why I entered it
        > there and why it is needed as
        > it doesn't seem to tie in with the code that follows.

        $name_found is acting as a flag. Each time through the loop the program
        sets $name_found to a known value (in this case 'N') then tests the keys
        in a hash to find a match in the foreach loop. If a key is found, the
        flag is changed to some other value ('Y' in this case).

        After the loop completes, the $name_found flag is tested to see if it
        has changed. Your program has to use line 112 because the flag must be
        initialized to some known value in order to test whether it has changed.

        I have found that my use of flags is generally a flaw in my logic or is
        the result of my ignorance of the features of the programming language I
        am using.

        I would probably do something like this, though I wouldn't be caught
        dead using "hash" as the name of a hash. :)


        # Simple hash lookup
        if ( exists $hash{$input_name} ) {
        printf qq{%s has the password: %s\n}, $input_name, $hash{$input_name};

        } else {
        print "Sorry, there is no such person found. Please try again.\n";
        }

        You can read up on the use of the "exists" function in perlfunc.

        HTH,

        Charles Clarkson
        --
        Mobile Home Investor
        Free Market Advocate
        Programmer

        Stephenville, TX
        http://www.clarksonenergyhomes.com/wordpress/about/
        http://twitter.com/CharlesClarkson
        +1 (254) 968-8328
      • Charles K. Clarkson
        ... A lot depends on what you mean by it didn t work ? Exactly how did it fail? Be precise. Here s my test (which works fine on Activestate perl version
        Message 3 of 5 , Dec 1, 2008
          Ethel Ann wrote:

          > Hi, Charles,
          > For the 2nd while(1), I tried inserting your code and commenting out
          > what I had, but it didn't work - what did I miss?

          A lot depends on what you mean by "it didn't work"? Exactly how did
          it fail? Be precise.

          Here's my test (which works fine on Activestate perl version 5.8.8):

          while (1) {

          print "\nNotice: You may enter 'exit' at any time to exit this
          loop.\n\n";
          print "Enter the last name, a comma, a space and then a first name
          to search.\n";
          print "For example: maines, natalie\n";

          # Cleanse user input
          chomp( my $input_name = <STDIN> );

          # Trim leading and trailing white space
          # - see FAQ 4
          $input_name =~ s/^\s+//;
          $input_name =~ s/\s+$//;

          # Exit program if user wants to go
          exit if $input_name eq 'exit';

          # Simple hash lookup
          if ( exists $hash{$input_name} ) {
          printf qq{%s has the password: %s\n}, $input_name,
          $hash{$input_name};

          } else {
          print "Sorry, there is no such person found. Please try again.\n";
          }
          }



          Charles Clarkson
          --
          Mobile Home Investor
          Free Market Advocate
          Programmer

          Stephenville, TX
          http://www.clarksonenergyhomes.com/wordpress/about/
          http://twitter.com/CharlesClarkson
          +1 (254) 968-8328
        • Charles K. Clarkson
          ... Asking questions (and answering questions) is the purpose of this list. ... In the perl documentation there are 9 perl FAQ files labeled perlfaq1 through
          Message 4 of 5 , Dec 1, 2008
            Ethel Ann wrote:

            > Okay, I got it to work, but have a new question for you.
            > (I hope you don't mind!)

            Asking questions (and answering questions) is the purpose of this list.


            > One of your comments says See FAQ4.
            > Where is that located? I would like to read it.

            In the perl documentation there are 9 perl FAQ files labeled
            perlfaq1 through perlfaq9. Look for a file named perlfaq4. There is an
            online version of the perl FAQ at the addresses below.

            http://faq.perl.org/ or http://perldoc.perl.org/index-faq.html

            The complete documentation (for perl v. 5.10.0) is available online
            at: http://perldoc.perl.org/

            My Activestate perl installation includes HTML documentation at:
            file:///C:/Perl/html/index.html

            I think Perlmonks (.com) and CPAN also have the perl documentation
            available.


            HTH,

            Charles Clarkson
            --
            Mobile Home Investor
            Free Market Advocate
            Programmer

            Stephenville, TX
            http://www.clarksonenergyhomes.com/wordpress/about/
            http://twitter.com/CharlesClarkson
            +1 (254) 968-8328
          • andy_bach@wiwb.uscourts.gov
            ... works, but if this is right, I don t understand why it needs to be where it is. Line 3 - %hash = (); It s an old cargo cult thing - or belts/suspenders,
            Message 5 of 5 , Dec 2, 2008
              > 1. Why does the first line of the code have to be an empty hash? It
              works, but if this is
              right, I don't understand why it needs to be where it is.
              Line 3 - %hash = ();

              It's an old 'cargo cult' thing - or belts/suspenders, I guess. You're
              assigning an empty list (the parens) to the hash, which would clear any
              existing values. Akin to:
              $name = '';

              The bigger issue here is the lack of lexical safety, if you do:
              my %hash;

              You don't need to worry about cleaning it out, as you're assured it was
              just created. Of course, the name 'hash' isn't very good either. You will
              see:
              my %hash = ();

              it's just extra typing and, maybe, slightly more obvious but entirely
              unnecessary. You really, really need to use lexical safety, in any program
              over ... 5 lines. It should be standard to start your scripts w/:
              use warnings;
              use strict;

              and, on this list, it should be a pretty standard response to any posted
              code - it should, at least, come in strict/warnings clean.

              $name_found = 'N'; #MY 2ND QUESTION IS ABOUT THIS LINE AND WHY IT WORKS
              HERE.
              foreach $name (@newarray)
              {
              if ("$input_name" eq "$name")
              {
              print $name." has the password ".$hash{$name}."\n";
              $name_found = 'Y';
              last;
              }

              } #close foreach
              if ("$name_found" eq 'N')
              {
              print "Sorry, there is no such person found. Please try again. \n";
              }

              This is a little odd - the point of a hash is you can fetch directly by key
              so:
              if ( exists $hash{$input_name} ) {
              print $name." has the password ".$hash{$name}."\n";
              }
              else {
              print "Sorry, there is no such person found. Please try again. \n";
              }

              does the same thing - no need to concat or refetch though:
              if ( my $pwd = $hash{$input_name} ) {
              print "$name has the password $pwd\n";
              }
              else {
              print "Sorry, there is no such person found. Please try again. \n";
              }

              If the assignment succeeds (that is, something 'exists' in %hash at the key
              $input_name) the 'if' carries through.
              -------------------
              Andy Bach
              Systems Mangler
              Internet: andy_bach@...
              Voice: (608) 261-5738 Fax: 264-5932

              If I have seen farther than others, it is because I was standing on the
              shoulders of giants. -- Isaac Newton
              In the sciences, we are now uniquely privileged to sit side by side
              with the giants on whose shoulders we stand. -- Gerald
              Holton
              If I have not seen as far as others, it is because giants were standing
              on my shoulders. -- Hal Abelson
              In computer science, we stand on each other's feet. -- Brian
              K. Reid
            Your message has been successfully submitted and would be delivered to recipients shortly.