#!/usr/bin/perl -w use 5.010; ############################################# # This document explains Perl's # Hash facilities # AAK: Last Modification # Tue Sep 11 22:10:27 PDT 2012 # ########################################### #Hash is like array but unsorted, and index could be #a string as well as numbers: #it is defined basically like : $hask{key} = value #where key is the same as index for array #and value is the correspoding value of the key: $student_num{"arman"} = "s2932832"; $student_num{"daoyan"} = "s8473272"; @people = qw/ arman daoyan /; foreach $person (@people) { say "${person}'s student ID is: $student_num{$person}"; } #you can refer to the hash as a whole via %hash: #another way to define a hash is: my %IPdatabase = ( "google" => '74.128.23.93', "ubc" => '137.32.42.154', "yahoo" => '67.32.45.190', ); #using reverse, you can swithc the keys with values and values with keys %RIPdatabase = reverse %IPdatabase; #using key operator you can list the keys in a hash #and operator values returns values in a hash @IPs = keys %RIPdatabase; @Sites = keys %IPdatabase; for $i (@IPs) { say "$i : $RIPdatabase{$i}"; } for $j (@Sites) { say "$j : $IPdatabase{$j}"; } #using each operator: while ( ($k, $v) = each %IPdatabase ) { say " $k , $v"; } $nc = keys %IPdatabase; #note the context dependency of perl, since $nc is a scalar # return of keys will be the number of keys which is size of database say "data base includes $nc data"; #using exist you can chech if a key exists in a hash or not: if ( ! exists $IPdatabase{"microsoft"} ) { say "Sorry! no microsoft available, why do you even need that?"; } #note that ! is the "NOT" operator #using delete you can delete an entry from a hash: delete $IPdatabase{yahoo}; @newkeys = keys %IPdatabase; say "you dont even need yahoo: @newkeys"; #one important hash is the enviroumental variable stored in %ENV: #it is similar to @ARGV, which stores the argument passed to the script #by user, when they run the program print "YOUR PATH IS: \n $ENV{PATH} \n";