in reply to Re^2: Recursive traversal of a HoH... and paths
in thread Recursive traversal of a HoH... and paths
Well I don't know what you mean by 'test', but if you want to do something on every node - internal as well as leaf - then something like this:
sub walk { my( $v, @path ) = @_; foo( @path ); if ( keys %$v ) { for my $k ( sort keys %$v ) { walk( $v->{$k}, @path, $k ); } } }
If that something might prevent recursion below the current node, then you could have it return a "prune" boolean:
sub walk { my( $v, @path ) = @_; foo( @path ) or return; # true means recurse if ( keys %$v ) { for my $k ( sort keys %$v ) { walk( $v->{$k}, @path, $k ); } } }
Of course, for an even more general solution, you'd want to be able to pass in the "callback":
sub walk { my( $cb, $v, @path ) = @_; $cb->( @path ) or return; # true means recurse if ( keys %$v ) { for my $k ( sort keys %$v ) { walk( $cb, $v->{$k}, @path, $k ); } } }
No doubt someone else will propose an iterator-based solution...
|
|---|