Please send questions to
st10@humboldt.edu .
#!/usr/bin/perl -w
#######################################################
# lab02_hash_functs
#
# try out a variety of Perl's hash functions:
# keys, values, each
#
# modified by Sharon Tuttle from "Learning Perl",
# by Schwartz and Phoenix
#
# last modified: 9-2-04
#######################################################
%order_totals = ("chocolate"=>13,
"hamburger"=>10,
"tofu dog"=>12,
);
@hold_order_totals = %order_totals;
print "@hold_order_totals\n";
# try out hash functions keys, values
@foods = keys %order_totals;
@quants = values %order_totals;
print "\nresult from keys: @foods\n";
print "result from values: @quants\n";
# in a scalar context, both keys and values return the number
# of elements in the hash;
$num_foods = keys %order_totals;
$num_quants = values %order_totals;
print "\n\$num_foods: $num_foods\n";
print "\$num_quants: $num_quants\n";
# iterating through a hash, attempt #1:
print "\ntrying foreach with a hash:\n";
foreach $item (%order_totals)
{
print "$item\n";
}
# BETTER way to iterate through a hash: function each
print "\ntrying each and while with a hash:\n";
while ( ($food, $quant) = each %order_totals )
{
print "$food => $quant\n";
}
# BUT --- if you need the keys in ASCIIbetical order...
print "\nin ASCIIbetical order of keys:\n";
foreach $food (sort keys %order_totals)
{
print "$food => $order_totals{$food}\n";
}
# end of lab02_hash_functs