-3

In Perl, from the below hash:

{
    'item3' => {
        'floors' => [ 'a', 'b', 'c' ]
    },
    'item1' => [ 'special' ]
    'item2' => {
        'books' => {
            'topics' => [ 'epics' ]
        },
        'sports' => [ 'tennis' ]
    },
    'item5' => {
        'groups' => {
            'teams' => [ 'x', 'y' ]
        }
    },
    'offers' => {
        'list' => [ 'bags' ]
    }
}

Need to parse only last values in each sub level of hash where it is always be an array.

Only final child entries(array values) need to be listed.

Expecting the output in one single array:

[ 'a', 'b', 'c', 'special', 'epics', 'tennis', 'x', 'y', 'bags' ]

no idea how to proceed....please help me to get rid of this.

Advance Thanks!!!!

Denis Ibaev
  • 2,470
  • 23
  • 29
Nike
  • 25
  • 5
  • 1
    What did you try? What happened? What did you expect? – asjo Dec 28 '13 at 16:17
  • You can use 'keys()' function to iterate trough hash. – alex Dec 28 '13 at 16:19
  • Looks like you dumped 5 separate hashes, not one big hash as you claim. Could you fix your question? – ikegami Dec 28 '13 at 16:21
  • 1
    You're going to have to recursively visit the data structure every time you find a `ref($value) eq 'HASH'`, and push the contents of the referenced array unto the result array every time you find a `ref($value) eq 'ARRAY'`. – ikegami Dec 28 '13 at 16:23
  • voting to close, no valid code to try and solve – Vorsprung Dec 28 '13 at 16:33
  • For avoiding confusion i didn't add my code sample and posted with the content which is similar to code sample....downvote...go ahead!!! my problem solved, check mpapec answer...I already accept it as my answer. Advance new year wishes to you all!!!! – Nike Dec 28 '13 at 17:56

1 Answers1

1

Recursion assumes that data structure consists of hashes and arrays only, and array elements are not references,

use strict;
use warnings;
use Data::Dumper;

my %h;
@h{ 1..5 } = (
    { 'item3' => { 'floors' => [ 'a', 'b', 'c' ] } },
    { 'item1' => [ 'special' ] },
    { 'item2' => {
                      'books' => { 'topics' => [ 'epics' ] },
                      'sports' => [ 'tennis' ]
                    }},
    { 'item5' => { 'groups' => { 'teams' => [ 'x', 'y' ] } } },
    { 'offers' => { 'list' => [ 'bags' ] } },
);

print Dumper [ arrvals(\%h) ];

sub arrvals {
  my ($ref) = @_;
  return ref($ref) eq "ARRAY"
    ? @$ref
    : map arrvals($_), values %$ref;
}
mpapec
  • 50,217
  • 8
  • 67
  • 127