in reply to Re: How to tie multilevel (multidimensional) hash?
in thread How to tie multilevel (multidimensional) hash?
Here's my driving code, test.pl. I can get it to read the second dimension on the subsequent FETCH, but can't figure out how to write the recursive routine. The only recursive way I know is if I can supply the next parameter (eg. $self->FETCH( $dimension ), or implicitly, $node->{ $dimension }, where $dimension would first be 'x' and secondly 'y'). But the hash tie() API only presents one dimension at a time. A neat thing I have learned, so far, is that for storing multidimensional hashes, that the ongoing case is that the value will be an anonymous hash, and the terminus case is that the value is a scalar.
#! /users/michwong/perl/bin/perl #! /users/michwong/perl/bin/perl -d:ptkdb use lib qw( . ); use MultiHash; tie %$hash, "MultiHash"; $hash->{ x }{ y } = 10; $hash->{ x }{ y };
Here's my module, MultiHash.pm
package MultiHash; sub TIEHASH { my ($class) = map { ref || $_ } shift; my $level = shift || 0; return bless { level => $level, data => {}, }, $class; } sub FETCH { my $self = shift; my $key = shift; if( UNIVERSAL::isa( $self, 'HASH' )) { print "($self) fetching '$key': $self->{ data }{ $key }\n"; } else { print "($self) fetching '$key': $self->{ data }{ $key }\n"; } return $self->{ data }{ $key }; } sub STORE { my $self = shift; my $key = shift; my $value = shift; RECURSE_CASE: { # ===== MULTIDIMENSIONAL HASH if( UNIVERSAL::isa( $value, 'HASH' )) { if( exists $self->{ data }{ $key } ) { $self->{ data }{ $key } = $value; print "($self) storing '$value' into '$key'\n"; } else { my $node; tie %$node, "MultiHash"; $self->{ data }{ $key } = $node; print "($self) storing '$value' into '$key' with new n +ode\n"; } last RECURSE_CASE; } if( UNIVERSAL::isa( $value, 'MultiHash' )) { if( exists $self->{ data }{ $key } ) { $self->{ data }{ $key } = $value; print "($self) storing '$value' into '$key'\n"; } else { my $node; tie %$node, "MultiHash"; $self->{ data }{ $key } = $node; print "($self) storing '$value' into '$key' with new n +ode\n"; } last RECURSE_CASE; } if( UNIVERSAL::isa( $value, 'SCALAR' )) { $self->{ data }; last RECURSE_CASE; } } return $value; } sub DELETE { my $self = shift; my $key = shift } sub FIRSTKEY { my $self = shift; my $temp = keys %{ $self->{ data }}; return scalar each %{ $self->{ data }}; } sub NEXTKEY { my $self = shift; return scalar each %{ $self->{ data }}; } 1;
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: My code (I can't figure out how to implicitly recurse)
by perrin (Chancellor) on Feb 12, 2003 at 03:14 UTC | |
by mikezone (Novice) on Feb 12, 2003 at 03:26 UTC |