Traversing a hash structure

From BioPerl
Jump to: navigation, search

Recursively:

dohash( \%h, sub { print "$_[0]\n" } );
 
sub dohash { 
my ($h, $callback) = @_; 
map { ref $$h{$_} ? dohash($$h{$_},$callback) : $callback->($$h{$_}) } keys %$h ; 
return; }

A depth-first iterator:

$it_d = make_depth_iterator( \%h, sub { print "$_[0]\n" } );
while ($it_d->()) {1;}
 
sub make_depth_iterator {
    my ($h, $callback) = @_;
    my @stack = shift;
    return sub {
	while (@stack) {
	    my $v = pop @stack;
	    while (ref($v)) {
		push @stack, values %$v;
		$v = pop @stack;
	    }
	    return undef unless $v;
	    return $callback->($v);
	}
	return;
    }
}

A breadth-first iterator:

$it_b = make_breadth_iterator( \%h, sub { print "$_[0]\n" } );
while ($it_b->()) {1};
 
sub make_breadth_iterator {
    my ($h, $callback) = @_;
    my @queue = shift;
    return sub {
	while (@queue) {
	    my $v = shift @queue;
	    while (ref($v)) {
		push @queue, values %$v;
		$v = shift @queue;
	    }
	    return undef unless $v;
	    return $callback->($v);
	}
	return;
    }
}

--MAJ

[back to top]


Personal tools
Namespaces
Variants
Actions
Main Links
documentation
community
development
Toolbox