Foundations
Hashes
Hashes store values by key, which is useful for lookups.
hash lookup
A hash key selects a stored value, such as `$prices{$item}`.
Hashes
hashes.pl
Replay: real traced execution (multi-file project)
use strict;
use warnings;
my %prices = (
apple => 2,
banana => 1,
pear => 3,
);
my $item = "apple";
my $price = $prices{$item};
print "item=$item\n";
print "price=$price\n";
use strict;
use warnings;
my %prices = (
apple => 2,
banana => 1,
pear => 3,
);
my $item = "banana";
my $price = $prices{$item};
print "item=$item\n";
print "price=$price\n";
use strict;
use warnings;
my %prices = (
apple => 2,
banana => 1,
pear => 3,
);
my $item = "pear";
my $price = $prices{$item};
print "item=$item\n";
print "price=$price\n";
%prices ← 3, $item ← apple, $price ← 2
4my %prices→ 3 = (5 apple => 2,6 banana => 1,7 pear => 3,8);910my $item→ apple = "apple"; #@item="banana", "pear"11my $price→ 2 = $prices{$item}2;1213print "item=$itemapple\n";14print "price=$price2\n";outputitem=apple price=2
%prices ← 3, $item ← banana, $price ← 1
4my %prices→ 3 = (5 apple => 2,6 banana => 1,7 pear => 3,8);910my $item→ banana = "banana";11my $price→ 1 = $prices{$item}1;1213print "item=$itembanana\n";14print "price=$price1\n";outputitem=banana price=1
%prices ← 3, $item ← pear, $price ← 3
4my %prices→ 3 = (5 apple => 2,6 banana => 1,7 pear => 3,8);910my $item→ pear = "pear";11my $price→ 3 = $prices{$item}3;1213print "item=$itempear\n";14print "price=$price3\n";outputitem=pear price=3
What Happens
%pricesstoresapple => 2,banana => 1, andpear => 3.$itemstarts as"apple".$prices{$item}looks up the value forapple.$pricebecomes2.- The program prints
item=appleandprice=2.
Hash Picture
| item | lookup | price |
| --- | --- | --- |
| apple | $prices{"apple"} | 2 |
| banana | $prices{"banana"} | 1 |
| pear | $prices{"pear"} | 3 |
Try It
Exercise: hashes.pl
Reproduce item=apple and price=2, then use the pinned items banana and pear to predict each price.