in reply to
iterators: traversing arbitrary data structure
Try using ref() to determine what is stored at each dimension. Then you can make the decision about how to iterate. I believe that this subroutine will do the trick, however, I am creating this off the top of my head, so please don't be afraid to criticize.
sub recIterate{
my $ref = shift;
my $funcRef = shift; #mutation function reference
if(ref($ref) =~ /HASH/){
my %copy = %$ref;
foreach my $item (keys %copy){
$copy{$item} = recIterate($copy{$item},
$funcRef);
}
%$ref = %copy;
}elsif(ref($ref) =~ /ARRAY/){
my @copy;
foreach my $item (@copy){
push(@copy, recIterate($item, $funcRef);
}
@$ref = @copy;
}elsif(ref($ref) eq ''){ #i think this is how scalars
#look to ref, but you might
#want to look it up
$$ref = &$funcRef($$ref);
}
}
In order to use this you must define what happens to each scalar value that is in the data structure with a subroutine that takes one scalar as a parameter and returns the new one. Just pass a reference to it when you call recIterate. Here is a usage example:
#you will need to define your own mutator function
sub someFunc{ #removes tabs
my $old = shift;
my $new = $old;
$new =~ s/\t//g;
return $new;
}
%nDimHash; #this might be a HoAoHoAoAoAoS or whatever;
%nDimHash = recIterate(\%recIterate, \&someFunc);
That should do the trick. Each dimension that is a hash or an array is rebuilt at that level and the previous dimension is is set to point to the new one. The garbage collector should clean up after us. Each scalar value in the example will have all tabs removed, but you can make the function do whatever you want.
One more word of caution, this will take some major overhead if you want to iterate a deep data structure. I hope this does the trick.
¥peace out guys, thanks for reading my first post, CaMelRyder¥