More on Perl Hashes Learning Objectives Hash of
More on Perl Hashes Learning Objectives: Hash of Hashes
Use of Hash: student l Simple hash as simple relations: $student{94001} = "Peter"; $student{94002} = "John"; 94001 Peter 94002 John
Hash of Hashes: student Key=Student # Values 94001 94002 … … COMP 111 A COMP 222 B COMP 333 C COMP 111 B COMP 222 B COMP 333 B
Pointers n n If a hash value is another hash table, you actually just have an address or a pointer in the memory Thus, you can access it by placing a % in front: n n $p=$student{94001} is the pointer, %$p is the hash table keys(%$p) returns the course names Key=Studen t# Values COMP 222 B COMP 333 C 94001 94002 … COMP 111 A … COMP 111 B COMP 222 B COMP 333 B
Hash of Hashes n foreach $s print } (keys(%student)) { "Student $s: "; "Name = $student{$s}{'name'}; "; "CGA = $student{$s}{'CGA'}n"; n foreach $s (keys(%student)) { $p=$student{$s}; # get the pointer to small hash foreach $c (keys(%$p)) { # $c is the course name print “Course Taken by student $s = $c: "; }
Hash of Hashes $ cat hash 3 #!/usr/local/bin/perl 5 -w $student{94001}{'grade'}= {"comp 111"=>'A', "comp 211"=>'B+'}; print $student{94001}{'grade'}{'comp 111'}; $p = $student{94001}{'grade'}; # $p is a ptr foreach $c (keys(%$p)) { # %$p - the hash pointed by p print "$c $$p{$c}n"; } # $$p{. . . } - an element of the hash pointed by p $ hash 3 comp 111 A comp 211 B+
- Slides: 6