#!/usr/bin/perl
#
# eg2: hash playground
#
# hash example.

print "building a roomno hash mapping usernames -> room number strings\n";
my %roomno = (
	"dcw" => "225", "ldk" => "225",
	"sza" => "225", "mjw03" => "228"
);

print "\nadding a few people to it.\n";
$roomno{susan} = "569";
$roomno{mjb04} = "225";
$roomno{gnb}   = "225";

print "\ndelete some good for nothing skiver from it..\n";
delete $roomno{dcw};

print "\nlook up an unknown person:\n";
print "  elvis has left the building\n" unless exists $roomno{elvis};

print "\ncheck several people - known or unknown?\n";
foreach my $person (qw(ldk susan elvis))
{
	if( exists $roomno{$person} )
	{
		my $room = $roomno{$person};
		print "  $person is in $room\n";
	} else
	{
		print "  unknown $person\n";
	}
}

print "\ndisplay all known info in unsorted order:\n";
foreach my $person (keys %roomno)
{
	my $room = $roomno{$person};
	print "  $person in room $room\n";
}

print "\ndisplay all known info in sorted-by-key order:\n";
foreach my $person (sort keys %roomno)
{
	my $room = $roomno{$person};
	print "  $person in room $room\n";
}

print "\ndisplay all known info in sorted-by-value order:\n";
foreach my $person (sort { $roomno{$a} cmp $roomno{$b} } keys %roomno)
{
	my $room = $roomno{$person};
	print "  $person in room $room\n";
}

print "\nidiomatic way of iterating over all (k,v) pairs\n";
while( my($person,$room) = each %roomno ) # foreach (key,value) pair in %roomno
{
	print "  $person in room $room\n";
}

print "\nbuild $inroom: a room->comma separated list of users hash\n";
my %inroom;
while( my($person,$room) = each %roomno ) # foreach (key,value) pair in %roomno
{
	if( exists $inroom{$room} )
	{
		$inroom{$room} .= ",$person";
	} else
	{
		$inroom{$room} = $person;
	}
}

print "\nnow print out all (room,list of people) pairs\n";
foreach my $room (sort keys %inroom)
{
	my $people = $inroom{$room};
	print "  $room: $people\n";
}
