_learning perl_, ch5, 1.1.2002, nh HASHES used to be called "associative arrays" ^^^^^^ a way to store data like an array, except the index value is not an integer, it's another piece of data (an arbitrary scalar called a "key") * its elements have NO PARTICULAR ORDER hash variable names: %[a-zA-Z][a-zA-Z0-9_]* --> %, letter, 0 or more letters, digits, or _s elements of hash %somehash accessed by $somehash{$key} assigning value: %fred{"nori"} = "orange"; %fred{"martin"}="yellow"; %fred{34} = "56.66666"; calling: $fred{34} += 3; # makes it 59.66666 copying: --since perl has no literal representation for a hash, you have to copy it to a list, then to another hash. @fred_list = %fred; # unwinds %fred into a list %different_hash = @fred_list; # creates %different_hash in same # order as original %fred ^^^^^^^^^^^^^^^^^^^^^^^ but never rely on order! it's | arbitrary! `-> can also copy just by saying %copy = %original; # copy hash table gets original hash table | `-> and can swap keys and values by saying %backwards = reverse (%original); # but this might be a bad # idea, as if two keys # have different values, HASH FUNCTIONS: # they'll end up as one -------------- # entry on the new list. * keys -- lists all keys in hash -- in scalar context, means number of elements in hash. while(keys(%somehash)) { # cycles while there are still elements in the hash # table, returning true, until there aren't ==> false } OR while (keys(%somehash) < 10) { # do some action # (here, keys(%somehash) is a numerical value } (actually, just if(%somehash) performs the same function -- tests to see if there are elements in it) * values -- lists all values in hash * each -- if you want to iterate over the whole hash, you can either look up every key and its corresponding value, or use EACH: each(%hashname) returns a key-value pair as a two-element list warning: adding new values to the entire hash RESETS EACH -- can be confusing! * delete -- deletes a key-value pair operand is the key: %fred = ("one", 1, "two", 2); delete $fred{"one"}; # %fred now just has ("two", 2); HASH SLICES: ----------- hash slices begin with '@': @score("fred","barney","dino") = (205,195,30); can also be used with variable interpolation: @players = qw(fred barney dino); print "scores are: @score{@players}"; can also be used to merge a smaller hash into a larger one: %league{keys %score} = values %score;