Title: Chapter 6
1Chapter 6 Hashes
2Hash Reputation
- Hashes are sometimes regarded as a difficult
subject in Perl - Due largely to misleading or inconsistant
syntax
3Objectives
- Objectives
- Use hash prefixes
- Initialize a hash
- Create a hash
- Load and search a hash
- Remove keys from hashes
4What are Hashes?
- A hash is an unordered collection of values, each
of which is identified by a unique key - A value can be retrieved by its key,
- one can add to or delete from the collection
- A data structure with these properties is called
a dictionary
Abhijit Menon-Sen (October 01, 2002 )How Hashes
Really Workhttp//www.perl.com/lpt/a/2002/10/01/h
ashes.html
5A Dictionary
- One simple way to implement a dictionary is to
use a linked list of keys and values (that is, a
list where each element contains a key and the
corresponding value). - To find a particular value, one would need to
scan the list sequentially, comparing the desired
key with each key in turn until a match is found,
or we reach the end of the list.
Abhijit Menon-Sen (2002)
6Problem
- This approach becomes progressively slower as
more values are added to the dictionary, - because the average number of elements we need to
scan to find a match keeps increasing.
Abhijit Menon-Sen (2002)
7Solution?
- Performing binary searches on a sorted array of
keys instead of using a linked list - but performance would still degrade as the
dictionary grew larger - Transform every possible key into a unique array
index, then we could store each value in a
corresponding array entry - although this strategy is simple and fast, it has
many disadvantages and is not always useful
Abhijit Menon-Sen (2002)
8Solution
- What we need is a practical compromise between
speed and memory usage - Hashes represent just such a compromise.
Abhijit Menon-Sen (2002)
9What are Hashes?
- Associative Arrays
- Same as a normal array
- It is a list of scalar values
- But, uses keys rather than a simple numeric
subscript or index - Array entries are called slots or buckets
- Most important thing
- Remember the order that you specify the hash
- Key ? then Data
10Hash Clarification
- The Hash provides a useful look up tool similar
to the key in a database table. - A unique key is used to locate a given value
- Hashes are uniformly fast
- Can get large with little degration in speed
- Hashes are useful for handling input from HTML
forms, CGI environment variables and more.
11Hash Prefix
- When you want to refer to the whole hash, use the
prefix - However, you can also use the and _at_ prefix
depending on what you are talking about.
12Examples
- If you are looking to return a single item from
the hash, you writeitem hashnamekeyvalue
You are using the hash to return a single
scalar value.
13Examples
- If you are looking to return a number of values,
you would use the array _at__at_arrayVal
_at_hashNamekey1, key2You are returning
multiple (array of) values.
14Example
- Supposing that you wanted to extract a subset of
one array._at_arraySub _at_hashName_at_arrayExtrYo
u have an array called _at_arrayExtr which contains
the keys you want to pull. This gets filtered
through the hash and the result is placed in
_at_arraySub
15Initializing a Hash
- The first thing to do is initialize the space.
16Creating the Hash
- Now lets add data. You can do it one at a time or
several at a time
17Multiple entries can be a pain
- Called the comma-arrow operator.
18Loading and Searching Hashes
- Weve already loaded the hash,
- Now lets print what we have
19The Result
Shark returned Jaws
keys in a loop printed each
20Or
Returns
21Add a single item to an existing hash
prodPrice (Crab gt 5, Tuna
gt 7, Shrimp gt 4) prodPrice'Be
ef' 10 foreach line(keys prodPrice)
print "line \n"
22Referencing a single item in a hash
prodPrice (Crab gt 5, Tuna gt
7, Shrimp gt 4) print
"prodPrice'Crab' \n\n" name 'Crab' value
prodPricename print "value \n\n"
Literal
Variable
23Two Great Sites
- http//www.devshed.com/c/a/Perl/Hash-Mania-With-Pe
rl/1/ - http//www.cs.mcgill.ca/abatko/computers/programm
ing/perl/howto/hash/
24Removing a key from the Hash
Note the syntax of the delete statement
Delete on the item with thekey value of Shark
25Results
26Now
- You can locate a single known item from the hash
with the simple commandvalue
animalsSharkwhich returned the value of
Jaws.
27Now
- This time, lets check to see if the hash value
exists
28Results
- Notice that Perl did not fail, it just printed
blanks
- So you will want to check the values existence
rather than assume
29Check for Existence
- Replace this into your program
30Check for Existence
Run it
31Results
- When you check the solution
32Lab 5
- In Lab 5 you will create an application that will
check the value of quantity on hand for a
particular item on demand. - Create a hash with the products and quantities.
You select the products and quantity values. You
must have at least 20 items in the hash.
33Lab 5
- Create a user interface.
- Include the company name
- Identification of the program
- List of available items
- A prompt for the user to enter the item name
- Validate the item name
- If the item does not match, display a message
similar to we do not carry that item - Prompt the user to enter another or quit
34Lab 5
- When you locate the item requested
- Allow the user to change the on hand quantity or
not - Validate the change amount
- Verify that the amount can be deducted from the
OHQ - If OHQ 10 do not allow deduction of 20
- NO NEGATIVE OHQ!
- If valid, deduct the amount and print the hash
- If not valid, return an error message and prompt
to try again or quit.
35Additional Fun
- You can also make 2 dimensional arrays in Perl
- A 2D array is essentially a hash where the value
is an array also. - You have to think about it like a table of values
where all of the data on each row is dependant on
the key of that row - Unlike a table, you cannot identify the elements
of the 2nd dimension by name
36Think like this
Item Name Cost Per Qty on Hand Qty on Hand Reorder Point
Crab 5 5 100 25
Tuna 6 6 50 10
Shrimp 4 4 75 10
Salmon 10 10 60 5
50 depends on Tunaor, 50 lbs refers to the
quantity on handof Tuna only
The data on the row is dependanton the key value
of the row
37Think like this
If I wanted to know how many lbs ofTuna I had, I
would start with the Key and work across
Item Name Cost Per Qty on Hand Qty on Hand Reorder Point
Crab 5 5 100 25
Tuna 6 6 50 10
Shrimp 4 4 75 10
Salmon 10 10 60 5
38Using this technique
- If we increased the number of offerings to
ltunlimitedgt - We would not have to ask for order quantities for
every single item - Rather, the user would enter the item to purchase
(say Tuna), - And after appropriate validation, the program
returns the price and on hand qty
39Using this technique
- Additionally,
- You store all of your data in one area
- You do not have to match single value arrays to
get all of the information that you need. - Array processing is less cumbersome,
- But,
- You need to remember the element order of the
values. - Or, you could accidently charge the qty on hand
as the price per pound