Hello Monks,

I would like to replace a key-value pair that is arbitrarily deep in a multi-level hash with only the value.
For example, I would like to turn the following hash:
my $element = { 'check' => { 'field' => 'OLK_BO_BK_TYPE' }, 'type' => 'case', 'case' => [ { 'value' => '1', 'resultset' => 'BROKER' }, { 'value' => '3', 'resultset' => { 'field' => 'OLK_BO_BK_DESC' }, }, ] };
into this:
my $element = { 'check' = 'OLK_BO_BK_TYPE', 'type' => 'case', 'case' => [ { 'value' => '1', 'resultset' => 'BROKER' }, { 'value' => '3', 'resultset' => 'OLK_BO_BK_DESC' }, ] };

replacing every occurence of field with just its value. Here's what I have so far:
hash_walk($element); sub hash_walk { my $element = shift; if(ref($element) =~ /HASH/ ) { foreach my $key (keys %$element) { if ($key =~ /field/) { # do something here? print "found $$element{$key}\n"; } hash_walk($$element{$key}); } } elsif (ref($element) =~ /ARRAY/) { foreach my $index (@$element) { hash_walk($index); } } }

Maybe a hash slice at the crucial point? Any help appreciated.
-micmac

In reply to replace a key with its value by micmac

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.