Greetings monks, I'm faced with a problem for which I surely could use some guidance:
I have to process a "tree" of user-supplied data, which is provided as a hash reference. Hash values can be scalars, arrays and hash references, which I happily recurse into, like this:
sub process {
my $node = shift;
if (my $reftype = ref($node)) {
return process_array($node) if $reftype eq 'ARRAY';
return process_hash($node) if $reftype eq 'HASH';
die "invalid node type: $reftype";
} else {
return process_scalar($node);
}
}
process({ 'a' => '1', 'b' => [ '2' ], 'c' => { 'd' => '3' } });
The example is contrived, but I think you get the picture (
process_array and
process_hash call
process on their respective values, eventually).
Now my users want to provide also "special" kinds of hashes, e.g. hashes with case-insensitive keys. Of course, tied hashes come to mind, which would be fine with me, since my function can stay happily unaware of whether its passed a reference to a plain or a tied hash.
However, there is some concern about the performance implication of tied hashes, and an OO interface has been suggested:
package Local::MyComp::Map;
sub new { ... }
sub get { ... }
sub set { ... }
sub keys { ... }
etc. etc.
Of course, my function would have to handle such
Map instances specially, e.g.
if (my $reftype = ref($node)) {
if (blessed($node) && $node->isa(Local::MyComp::Map) {
process_map($node);
}
...
with
process_map using the
Map's
keys and
get methods to iterate over its elements.
So I'm asking the Perl monks:
Do the performance implications of tied hashes really warrant the introduction of a class that in fact just behaves like a tied hash (but with an OO interface)?
I.e., would using a special class for this purpose be really more efficient than using a tied hash?