Thursday, June 26, 2008

Perl: hashes of unknown elements

#!/usr/bin/perl
# Filename:                unpack.pl
# Description:             Unpacks hash of unknown types
# Supported Langauge(s):   Perl 5.8.x
# Time-stamp:              <2008-06-26 21:47:59> 
# -------------------------------------------------------- 
use strict;
# This is an array of strings
my @array = ("arr1", "arr2");
# This is a "predicable" hash, each string maps to a string:
my %hash = (
    'key0' => 'val0',
    'key1' => 'val1',
);
# This is an "unpredictable" hash:
my %mixed = (
    'key0' => 'string', 
    'key1' => \@array, 
    'key2' => \%hash,
);
# Note that I had to use '\' to indicate that I'm building 
# this hash with references to the previous array and hash. 
# I.e. not the array or hash itself, but a reference to it. 
# 
# I say this hash is unpredictable because it might seem 
# tricky recurse throuh it if you didn't know the mapping: 
# if key0 mapped to @array and key1 mapped to %hash etc. 
# -------------------------------------------------------
# Perl's dumper works: 
use Data::Dumper;
print Dumper(\@array);
print Dumper(\%hash);
print Dumper(\%mixed);
# -------------------------------------------------------
# Let's recursively loop through each:
print "Array:\n";
foreach my $str (@array) {
    print "\t" . $str . "\n";
}
# -------------------------------------------------------
print "Hash:\n";
foreach my $key (keys %hash) {
    print "\t" . $key . " --> " . $hash{$key} . "\n";
}
# -------------------------------------------------------
print "\nMixed:\n";
foreach my $key0 (keys %mixed) {
    print "\t" . $key0 . " => ";
    my $unknown = $mixed{$key0};
    if (ref($unknown) eq 'HASH') {
 print "{";
 foreach my $key1 (keys %$unknown) {
     # dereference with $$
     print $key1 . " => " . $$unknown{$key1} . ", ";
 }
 print "}";
    }
    elsif (ref($unknown) eq 'ARRAY') {
 print "[";
 foreach my $str (@$unknown) {
     print $str . ", ";
 }
 print "]";
    }
    else { # it's a string
 print $unknown;
    }
    print "\n";
}

No comments: