Lists, Arrays, and Hashes
Hash Lookup
A hash maps keys to values, and a lookup reads the value for one key.
hash lookup
A hash lookup uses a key inside braces to read one stored value.
Hash Lookup
hash_lookup.pl
Replay: real traced execution (multi-file project)
use strict;
use warnings;
my %scores = (
perl => 95,
go => 88,
ruby => 91,
);
my $key = "go";
my $value = $scores{$key};
my $found = exists $scores{$key} ? "yes" : "no";
print "key=$key\n";
print "found=$found\n";
print "value=$value\n";
use strict;
use warnings;
my %scores = (
perl => 95,
go => 88,
ruby => 91,
);
my $key = "perl";
my $value = $scores{$key};
my $found = exists $scores{$key} ? "yes" : "no";
print "key=$key\n";
print "found=$found\n";
print "value=$value\n";
use strict;
use warnings;
my %scores = (
perl => 95,
go => 88,
ruby => 91,
);
my $key = "ruby";
my $value = $scores{$key};
my $found = exists $scores{$key} ? "yes" : "no";
print "key=$key\n";
print "found=$found\n";
print "value=$value\n";
%scores ← 3, $key ← go, $value ← 88, $found ← yes
4my %scores→ 3 = (5 perl => 95,6 go => 88,7 ruby => 91,8);9my $key→ go = "go"; #@key="perl", "ruby"10my $value→ 88 = $scores{$key}88;11my $found→ yes = exists $scores{$key}88 ? "yes" : "no";1213print "key=$keygo\n";14print "found=$foundyes\n";15print "value=$value88\n";outputkey=go found=yes value=88
%scores ← 3, $key ← perl, $value ← 95, $found ← yes
4my %scores→ 3 = (5 perl => 95,6 go => 88,7 ruby => 91,8);9my $key→ perl = "perl";10my $value→ 95 = $scores{$key}95;11my $found→ yes = exists $scores{$key}95 ? "yes" : "no";1213print "key=$keyperl\n";14print "found=$foundyes\n";15print "value=$value95\n";outputkey=perl found=yes value=95
%scores ← 3, $key ← ruby, $value ← 91, $found ← yes
4my %scores→ 3 = (5 perl => 95,6 go => 88,7 ruby => 91,8);9my $key→ ruby = "ruby";10my $value→ 91 = $scores{$key}91;11my $found→ yes = exists $scores{$key}91 ? "yes" : "no";1213print "key=$keyruby\n";14print "found=$foundyes\n";15print "value=$value91\n";outputkey=ruby found=yes value=91
Look Up a Key
%scoresstores scores forperl,go, andruby.$keyisgo.exists $scores{$key}reportsyes.$scores{$key}reads the value88. | Key | Value | | --- | --- | |perl|95| |go|88| |ruby|91|
Exercise: hash_lookup.pl
Look up one hash key, print whether it exists, and print its value