Perl Variables: Hash Web Programming
Hash (Associative Array) Syntax key and value pair %hash = (key1, value1, key2, value2, ….); Hash Elements $hash{keyN} = valueN; Assigning values intialization %hash = (element list); %hash = @array; %hash = (key1=>value1, key2=>value2, …); assigning values to individual hash element $hash{“key1”} = “value1”; Hash elements are stored in a random order Example script Web Programming
Hash Functions @keys = keys (%hash); @values = values (%hash); return an array of hash keys @values = values (%hash); return an array of hash values (key,value) = each (%hash); return a key-value pair sequentially delete ($hash{key}); deletes a hash element exists ($hash{key}) returns true if key exists in %hash Example script Web Programming
Printing Hash print %hash; print join (“:”,%hash); hash is collapsed into an array and then printed i.e. print @hash print join (“:”,%hash); hash collapsed into array is joined and printed i.e. print join (“:”,@hash) while (($key, $value) = each %hash) { print “$key=$value\n”; } foreach $key (sort keys %hash) { print “$key=$hash{$key}\n”; } Example script Web Programming
Hash Examples Word Count open(IN,$file) || die “can’t open $file”; @lines=<IN>; close IN; foreach $line(@lines) { @words= split(/ +/,$line); foreach $wd(@words) { $wdcnt{$wd}++; } } Example script Web Programming