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

Hi Monks!
I have the following sturcture:
{ "tool": "A", "version": "1.3", "dependencies": [ { "tool": "B", "version": "8.23", "dependencies": [] }, { "tool": "C", "version": "2.1", "dependencies": [ { "tool": "D", "version": "1.1", "dependencies": [] } ] } ] }
You can think of this data structure as a tree:
A / \ B C | D
I want to do a postorder traversal on this tree and to be able to print the tool/version. So I get:
B/8.23 D/1.1 C/2.1 A/1.3
The problem is that I'm not sure how to to do it. I need to find each leaf and then remove it (???) in order to mark that "I was here". I'm sure that there is a better way to handle it and this is why I'm asking here. Is it possible to suggest a better way?

Replies are listed 'Best First'.
Re: Postorder on hash structure
by Corion (Patriarch) on Aug 08, 2021 at 16:16 UTC

    Recursion is a good approach here.

    Consider the following example code that prints an array. You basically have two cases:

    1. The item passed does not have dependencies - print the item
    2. The item passed has references - for each reference, handle it by recursing, then print the item itself

    In rough code, this would look like the following:

    sub print_item_dependencies( $item ) { for my $dep (@{$item->{dependencies}}) { print_item_dependencies( $dep ); } say join "/", $item->{tool}, $item->{version} }
Re: Postorder on hash structure
by tybalt89 (Monsignor) on Aug 08, 2021 at 17:07 UTC
    #!/usr/bin/perl use strict; # https://perlmonks.org/?node_id=11135697 use warnings; my $structure = { "tool" => "A", "version" => "1.3", "dependencies" => [ { "tool" => "B", "version" => "8.23", "dependencies" => [] }, { "tool" => "C", "version" => "2.1", "dependencies" => [ { "tool" => "D", "version" => "1.1", "dependencies" => [] } ] } ] }; printsubstructure($structure); sub printsubstructure { my $hashref = shift; printsubstructure($_) for @{ $hashref->{dependencies} }; print "$hashref->{tool}/$hashref->{version}\n"; }
Re: Postorder on hash structure
by karlgoethebier (Abbot) on Aug 08, 2021 at 15:43 UTC