Create the Hash

The first few times you look at the coding hash tables it can be a little confusing initially.  Before we get into how to set it up, it is worth understanding what it is.  I found the following Microsoft TechNet  article useful when I first started looking into creating hash tables.

Additionally, before the actual table was created, there were some initial setup steps that needed to be done.  First, we needed to collect a little info from the user.  



Now we have variables $where and $what that we can use.  

Next I like to "initialize" a few variables and the table.  Some of these steps are not really required; but the code runs, and old habits are hard to break.



The last line $hash.add(1,... adds the first entry in the table.  This is added so that the table will have a line that we can use to either break our of the script or search again.  For example, maybe there was a typo when they entered what they were looking for.  $count is a variable that we will come back to later.

There was also the variable $scripts that was covered earlier when we set our path.

Now we are ready to create the hash.  Depending on how comfortable you are with loops, this can look a little worse than it really is.



Here are the basic components:

1) There is and IF / ELSEIF test of the variable $where.  If the user wants to search script names the it is handled in the first IF test.  If the user wants to search the script content, it is handled by the ELSEIF section.

2)  Both of the IF conditions contain a Foreach loop that are very similar in function.  Each item that was found when we created $scripts will an iteration of the loop.  Inside the loop, there is an If statement that looks to see if the item matches $what we were asked to look for.  When a match is found, we add 1 to $count and we create an entry in the hash table.


No comments:

Post a Comment