rose has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks,

I want to use grep or map for the following refrence to find the child keys of 'Orange'.

use warnings; use strict; my $xml = { 'Fruits' => [ { 'Season' => { 'Apple' => { 'UnitsAvailable'=> ['100'] }, 'Orange' => { 'UnitsAvailable' => ['200'] } } } ] };

I tried the following code, but it is not finding

my @res = grep (/Orange/, $xml);

Please help to find the child keys of Orange.

Thanks
Rose

Replies are listed 'Best First'.
Re: grep in hash of array
by Corion (Patriarch) on Aug 05, 2008 at 12:15 UTC

    grep does not work that way. grep searches through a list and returns the elements for which a given predicate is true.

    It seems to me, from the name of your variable, that you would be better served by a different tool, in this case XML::LibXML or XML::XPath or XPath expressions in general.

      Is it not possible to find without using any module?

      Thanks
      Rose

        Of course it is possible to find this out without using any module, because even modules are written in Perl.

        So, if you want to do this the hard way, you best start learning about data structures via perlreftut and perldsc. Then take a look at Data::Diver and its code. That's it.

Re: grep in hash of array
by apl (Monsignor) on Aug 05, 2008 at 12:29 UTC
    Are you certain that's $xml and not %xml?

    In any event, it's your structure. Will you always be looking $key3 in $cml{$key1}{$key2}{Orange}{$key3}? If so, you need three loops. Are you saying Orange can be a key anywhere in the structure?

    What I'm trying to say (poorly) is that a little more in the way of detail will result in a more focused answer being produced.

Re: grep in hash of array
by chakram88 (Pilgrim) on Aug 05, 2008 at 16:50 UTC
    I want to use grep or map for the following refrence to find the child keys of 'Orange'.

    My bold emphasis added.

    my @o_kids = map { keys %{$xml->{Fruits}[0]{'Season'}{$_}} } grep /orange/i, keys %{$xml->{Fruits}[0]{'Season'}};

    Uses all the keywords from your question. But I suspect, as other have mentioned, that you are not asking the right question.

    Note that this solution requires you to know that (1) Fruits is an array ref (2) Orange is a key to the 'Seasons' hashref, etc. All of which means you have a rather intimate knowledge of the data structure. Unless this is homework in how to use grep, map (and aparently foreach), there is something else you're trying to accomplish.

Re: grep in hash of array
by JavaFan (Canon) on Aug 05, 2008 at 12:45 UTC
    For the given example, the following ought to do (but I haven't tested it):
    $orange = $$xml{Fruits}[0]{Season}{Orange};
    But I suspect that this isn't your real question.