I'm trying to search a nested structure and return an array with references to all occurrences that match something like:
->{foo}->{bar} or ->{foo}->[0]->{bar}
My recursive function (below) works fine for single instances like ->{bar} but somehow creates an endless loop with multiple parts (i.e ->{foo}->{bar}).
I think it has something to do with the eval corrupting $data but I dont understand why or how to fix it.

Any help would be appreciated.

The function:
sub rec_data { my $path = shift; # ->{foo}->{bar} my $data = shift; # nested perl structure my @results; # nothing to search return unless ref $data; # stop the evals complaining no warnings 'all'; if (ref $data eq 'HASH') { foreach my $k (keys %$data) { my $ref = qq|\$data->{$k}$path|; if (my $val = eval($ref)) { push @results, ref($val) ? $val : eval "\\$ref"; } if (ref $data->{$k}) { push @results, rec_data($path, $data->{$k}); } } } elsif (ref $data eq 'ARRAY') { foreach my $k (@$data) { my $ref = qq|\$k$path|; if (my $val = eval($ref)) { push @results, ref($val) ? $val : eval "\\$ref"; } if (ref $k) { push @results, rec_data($path, $k); } } } return @results; } # test data my $data = { test => { foo => { bar => 'bar', baz => 'baz' }, bar => { baz => 'baz' }, } } # search my @results = rec_data('->{foo}->{bar}', $data);

In reply to searching nested structures by IOrdy

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.