Download presentation
Presentation is loading. Please wait.
Published byGeorgia Gordon Modified over 9 years ago
1
Perl Chapter 5 Hashes
2
Outside of world of Perl, know as associative arrays Also called hash tables Perl one of few languages that has hashes built-in
3
Structure of Hashes Hashes are lists of scalar values BUT have string indices (called keys) keys also stored in structure variable name starts with % have their own namespace (like arrays) need not be declared, grow and shrink no way to determine order internal has function to store and retrieve
4
literals no hash literals (use list literals) (“bob”, 42, “carol”, 40, …) or use => instead of comma (“bob” => 42, “carol” => 40, …) or (bob => 42, carol => 40, …) – do not need “ “’s, left of => implicitly quotes barewords
5
first is actually a list, odd subscripted elements of array keys of the hash @list = (Bob, 42, Carol, 40); %ages = @list; same as %ages =(“bob” => 42, “carol” => 40); must be even length! %salaries = (“Bob” => 79_500, “Carol” => 43_000);
6
accessed by “subscripting” with key $salaries{“Bob”} 79500 insert new values $salaries{“Mike”} = 51_950; if Mike not in table, adds it if Mike is in table, changes value set to empty %salaries = (); undef %salaries NOT %salaries = undef; (1 element, undef)
7
printing hash variables not interpolated in double- quoted strings print “%salaries\n”; – prints %salaries print %salaries; – prints keys and values, no spaces
8
slice of hash gives us a list or array @some_salaries = @salaries{“Bob”, “Mike”}; @some_salaries (79500, 51950) note the @ form of the variable since slice of a hash is an array, can be interpolated in double quoted strings
9
operators delete $salaries {“Billie”}; – key and salary deleted from %salaries if (exists $salaries{“Billie”}) … – to find out if in hash
10
keys and values operators keys and values of a hash are arrays keys operator list of keys values operator list of values %highs=(“mon”=>64, “tue”=>66, “wed”=>72, “thu”=>55, “fri”=>35); @days = keys %highs; #array context @days is (“mon”, “tue”, “wed”, “thu”, “fri”)
11
foreach foreach $day (@days) { … } or foreach $day (keys %highs){ print “on $day,the temp was $highs{$day}\n”; } ^hashing of course, can sort (sort (keys %highs)) keys in scalar context $length = keys %highs;
12
values operator @temps = values %highs; foreach $temp (values %highs){ print “$tep\n”; }
13
Process pairs use each operator to return next element ($day, $temp) = each %highs; usually iterate on it while (($day, $temp)= each %highs){ print “On $day, the high temp was $temp.\n”; } cannot add to hash in loop body, if keys or each used in loop
14
in boolean expression if (%highs) … scalar context –> boolean expression, true if hash not empty
15
Predefined hashes – %ENV in first example When to use array vs. hash – when you have many accesses to specific elements
16
Examples freq.pl FindFiles.pl
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.