Thread Hash Struktur rekursiv durchsuchen
(2 answers)
Opened by bianca at 2013-10-15 18:38 Code (perl): (dl
)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 my @result = search(\%hash, 'foo'); sub search { my ($hash, $search) = @_; my @result; for my $key (keys %$hash) { my $found = search_data($hash->{ $key }, $search); push @result, $key if $found; } return @result; } sub search_data { my ($ref, $search) = @_; if (ref($ref) eq 'HASH') { for my $key (keys %$ref) { return 1 if $key =~ m/$search/; return 1 if search_data($ref->{ $key }, $search); } } elsif (ref($ref) eq 'ARRAY') { for my $item (@$ref) { return 1 if search_data($item, $search); } } elsif (ref($ref) eq 'SCALAR') { return search_data($$ref, $search); } elsif (ref($ref) eq 'REF') { return search_data($$ref, $search); } elsif (ref($ref) eq '') { return 1 if $ref =~ m/$search/; } return 0; } Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live. -- Damian Conway in "Perl Best Practices"
lesen: Wie frage ich & perlintro brian's Leitfaden für jedes Perl-Problem |