If you want to trundle through an arbitrarily deep reference tree with grep-like syntax, it's actually fairly easy to implement:

use 5.016; # For __SUB__, or pre-declare $grep and use $grep->() s +yntax sub ref_grep(&$) { my ($wanted, $ref) = @_; my $seen = {}; # Refs we've already seen (avoid circular refs) my @found; # Result list my $grep = sub { my ($ref, $path) = @_; return if ref $ref and $seen->{$ref}++; { $_ = $ref; push @found, $path if $wanted->() } for (ref $ref) { when ('HASH') { __SUB__->($ref->{$_}, $path."->{$_}") for sort key +s $ref; } when ('ARRAY') { __SUB__->($ref->[$_], $path."->[$_]") for sort key +s $ref; } } }; $grep->($ref, ''); return @found; }

Invocation is just like grep:

    say "Found value2: \$hash$_" for ref_grep { $_ eq 'value2' } $hash;

It's not limited to scalars, either; the BLOCK can perform any test it likes.

Of course, this is not without limitations. Support for nested objects, tests based on the path itself, pruning, etc., would take more work, and I'd certainly not try much harder to re-invent this wheel. What I'm saying is, take this as a starting point.

use strict; use warnings; omitted for brevity.

In reply to Re: grepping the location of a value from a datastructure by rjt
in thread grepping the location of a value from a datastructure by rastoboy

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.