Perl references
General December 9th, 2004
People who aren’t perl geeks can skip over this entry.
A reference in perl is like a pointer in C; it’s a scalar that acts as a location to another data structure. References allow you to get the most out of perl’s three native data structures – the scalar, the list, and the hash. Perl doesn’t support multidimension arrays, but it does let you have an array of references, where each reference can point to another array. References are pretty slick, as I can have a hash of a hash of a hash.
The problem is I don’t use references that much, and each time I need them I have to relearn them. Specifically, using n-dimensional hashes and foreach loops. So, here’s my blog entry so the next time I’m looking for info on references, I can start here.
Old newsgroup post explaining references
Perldoc’s perlreftut – Mark’s very short tutorial about references
My latest code snippet that seems to work with this data construct:
$MASTER{”2004-11-04″}{”2302-g”}{”users”}{”mussulma”} = 3;
foreach my $day (sort keys %MASTER) {
print "$day\n";
foreach my $radio (sort keys %{$MASTER{$day}}) {
print "\t$radio\n";
foreach my $tub (sort keys %{$MASTER{$day}{$radio}}) {
print "\t\t$tub\t\t\t\t(Max unique ";
my $uniq = scalar keys %{$MASTER{$day}{$radio}{$tub}};
print $uniq;
print ")\n";
foreach my $val (sort keys %{$MASTER{$day}{$radio}{$tub}}) {
print "\t\t\t$val (" . $MASTER{$day}{$radio}{$tub}{$val} . ")\n";
}
$ap = radio_to_ap($radio);
if ($tub eq "macs" or $tub eq "users") {
print FH "$day,$DATE{$day},$ap,$tub,$uniq\n";
}
if ($tub eq "totaltraffic") {
print FH "$day,$DATE{$day},$ap,$tub," . $MASTER{$day}{$radio}{$tub}{"total"} . "\n";
}
}
}
The part that always makes me stumble for a bit is using the foreach loops. I suppose I could do each nested foreach loop with the data reference I used in the previous foreach, but I find it easier just to keep the whole data structure intact. There’s probably a better way to do this.
About