Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

Re: recursive complex structure or something like that?

by gmax (Abbot)
on Jul 26, 2003 at 08:10 UTC ( #278071=note: print w/replies, xml ) Need Help??


in reply to recursive complex structure or something like that?

I believe that Tree::DAG_Node should serve your purposes.

Just to give you an example:

#!/usr/bin/perl -w use strict; use Tree::DAG_Node; my $vocabulary = Tree::DAG_Node->new; $vocabulary->name("vocabulary"); my $vehicles = Tree::DAG_Node->new; $vehicles->name("vehicles"); my $animals = Tree::DAG_Node->new; $animals->name("animals"); $animals->new_daughter->name("domestic"); $animals->new_daughter->name("wild"); ($animals->daughters)[0]->new_daughter->name("dog"); ($animals->daughters)[1]->new_daughter->name("tiger"); my $sciences = Tree::DAG_Node->new; $sciences->name("sciences"); $vocabulary->add_daughters($animals, $sciences, $vehicles); print "tree\n"; print map "$_\n", @{$vocabulary->draw_ascii_tree}; print "\ndump names\n"; print $vocabulary->dump_names; print "\nanimals and descendants\n"; print join(",", map {$_->name} $animals->self_and_descendants), "\n"; __END__ tree | <vocabulary> /--------------+----------\ | | | <animals> <sciences> <vehicles> /---------\ | | <domestic> <wild> | | <dog> <tiger> dump names 'vocabulary' 'animals' 'domestic' 'dog' 'wild' 'tiger' 'sciences' 'vehicles' animals and descendants animals,domestic,dog,wild,tiger

One of the great features of Tree::DAG_Node is that you can use the module to build your structure, and then export it to a list of lists.

my $lol =$vocabulary->tree_to_lol; my $code =$vocabulary->tree_to_lol_notation({multiline=>1}); print "$code\n"; __END__ [ [ [ [ 'dog' ], 'domestic' ], [ [ 'tiger' ], 'wild' ], 'animals' ], [ 'sciences' ], [ 'vehicles' ], 'vocabulary' ],

You can save the code in text mode and then eval it, or you can use Storable to store it and then retrieve it from another script.

Update. It also works the other way around, i.e. you can create a new tree from a lol using the appropriate constructor Tree::DAG_Node->lol_to_tree.

See the basics in Introduction to Tree::DAG_Node (in Tutorials). Be aware that Tree::DAG_Node does not handle circular references, AFAIK.

 _  _ _  _  
(_|| | |(_|><
 _|   

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://278071]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (8)
As of 2019-10-17 12:29 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Notices?