Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

Re: searching nested structures

by Roger (Parson)
on Jan 05, 2004 at 03:34 UTC ( [id://318756]=note: print w/replies, xml ) Need Help??


in reply to searching nested structures

use strict; use warnings; use Data::Dumper; # test data my $data = { test => { foo => { bar => 'bar', baz => 'baz', bul => { foo => { bar => 'bul' } } }, bar => { baz => 'baz' }, }, foo => { bar => 'foo' }, }; my $found = rec_data('->{foo}->{bar}', $data); print Dumper($found); print "--- array of ref's ---\n"; print "$_\n" for @$found; # verify by hand print "--- verify by hand ---\n"; print \$data->{foo}->{bar}, "\n", \$data->{test}->{foo}->{bar}, "\n", \$data->{test}->{foo}->{bul}->{foo}->{bar}, "\n"; sub rec_data { my ($pattern, $data) = @_; return if ref($data) ne 'HASH'; my @keys = keys %$data; # persist the value of the keys return if !@keys; my @found; # do we see pattern? if (eval 'exists $data' . $pattern) { push @found, eval '\$data' . $pattern; } # traverse the 'children' # foreach (keys %$data) will not work and will result # in deep recursion foreach (@keys) { # get the value of each key my $result = rec_data($pattern, $data->{$_}); next if ! $result; push @found, @$result; } return(\@found); }
And the output is -
$VAR1 = [ \'foo', \'bar', \'bul' ]; --- array of ref's --- SCALAR(0x167bdc) SCALAR(0x167b4c) SCALAR(0xf4a50) --- verify by hand --- SCALAR(0x167bdc) SCALAR(0x167b4c) SCALAR(0xf4a50)

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://318756]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others examining the Monastery: (3)
As of 2024-04-19 20:13 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found