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 37 38 39 40 41 42 43 44 45 46 47 48 49 50
#!/usr/bin/perl use strict; use warnings; use diagnostics; my %hash = ( strang1 => { string => 'string foo1', hash => { 'key foo2' => 'value foo3', }, array => [ 'foo4 im Array0', 'foo5 im Array1', ], }, ); print rekursive_hash_suche(\%hash,'foo'); sub rekursive_hash_suche { my ($ref,$suche) = @_; my %algo; $algo{SCALAR} = sub { my ($ref,$suche) = @_; my $fund = 0; $fund = 1 if $ref =~ /foo/; $fund; }; $algo{ARRAY} = sub { my ($ref,$suche) = @_; my $fund = 0; foreach my $k (@$ref) { my $fund = $algo{ref($ref->{$k})}($ref,$suche); last if $fund; } $fund; }; $algo{HASH} = sub { my ($ref,$suche) = @_; my $fund = 0; foreach my $k (keys %$ref) { print "ref:".ref($ref->{$k})." in ".$ref->{$k}."\n"; my $fund = $algo{ref($ref->{$k})}($ref,$suche); last if $fund; } $fund; }; return $algo{HASH}($ref,$suche); }
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; }