Close

August 5, 2009

Complex Perl Hashes

Perl is one of my absolute favorite languages to prototype in. While very easy to model complex object structures, the syntax of Perl Hashes can get a bit tricky to remember. This is just a quick “Get Started” guide that I hope will be useful to other developers.

Perl Hashes, to me, are the most powerful tool in the Perl language’s corner. It enables you to quickly setup ordered data structures without initialization/instantiation and fuss. Below is a sample structure to quickly model an object of a person. Please note there are about 50 different ways to write the following code, but for clarity and ease of demonstration I’m going with the following.

my %iObj=();  #setup main object
 
#I use references in this case because it helps me visualize the attributes easier
#you could also do: $iObj{$id}{TAGS}{FNAME}="Jeremy";
my $id=1;  #unique identifier for person
$iObj{$id}->{IDENT}->{FNAME}="Jeremy";
$iObj{$id}->{IDENT}->{LNAME}="Silva";
$iObj{$id}->{IDENT}->{ALIAS}="jts";
 
#For each Login Date, store HOW many times they logged in per the day.
$iObj{$id}->{LOGIN_DT}->{"12/01/08"}=2;
$iObj{$id}->{LOGIN_DT}->{"12/01/08"}=5;
$iObj{$id}->{LOGIN_DT}->{"12/31/08"}=6;
 
 
my $id=2;  #unique identifier for person
$iObj{$id}->{IDENT}->{FNAME}="Another";
$iObj{$id}->{IDENT}->{LNAME}="Person";
$iObj{$id}->{IDENT}->{ALIAS}="ap";
 
#For each Login Date, store HOW many times they logged in per the day.
$iObj{$id}->{LOGIN_DT}->{"11/01/08"}=12;
$iObj{$id}->{LOGIN_DT}->{"10/01/08"}=25;
$iObj{$id}->{LOGIN_DT}->{"11/31/08"}=16;
 
#Now to print out our data for our structure
for my $id ( keys %iObj ) {
	#we get EACH id from the main structure.  This is our
	#unique person id
	print "\n First Name:".$iObj{$id}->{IDENT}->{FNAME};
	print "\n Last Name:".$iObj{$id}->{IDENT}->{LNAME};
	print "\n ALIAS:".$iObj{$id}->{IDENT}->{ALIAS};
	#Now for this person, iterate and display their login information
	for my $dt (sort keys %{$iObj{$id}->{LOGIN_DT}}) {
		#we get EACH date/time from the LOGIN_DT for the person
		#we use the $dt to "KEY" into the LOGIN_DT reference...to get our "hits"
		print "\n\t Logged in: $dt ".$iObj{$id}->{LOGIN_DT}->{$dt}." times";
	}
	#add a return to separate the user
	print "\n\n";
}

The sample demonstrates a very simple way to model basic information into an easy to use structure. While the syntax for the secondary “For” loop is a bit tricky (getting a referenced hash), it certainly makes the language a very powerful tool in a data integrator’s tool box.

What’s also nice is that the hash object can reference nearly any object (arrays/hash/integers/etc) and is only size limited based on the operating system’s constraints.