package Isanchez; use strict; use Carp; our $VERSION = '0.01'; sub new { my ($class, $file) = @_; my $self = bless {}, $class; $self->_build($file); return $self; } sub _build { my ($self, $file) = @_; croak "Unable to retrieve data" unless open(INPUT,$file); while (<INPUT>) { my @field = split; unless (@field == 3 && $field[0] =~ /^\d+$/ && $field[0] =~ /^ +\d+/) { carp "Unable to parse\n$_"; next; } $self->{$field[2]}{decendent} = $field[0]; push @{$self->{decendents}[$field[1]]}, $field[2]; } } sub get_decendents { my ($self, $origin) = @_; croak "You must enter an origin in the tree" unless $origin; croak "$origin can not be found" unless exists $self->{$origin}; my $index = $self->{$origin}{decendent}; my @list = @{$self->{decendents}[$index]} if exists $self->{decend +ents}[$index]; return $origin unless @list; my @decendents = ($origin); while (@list) { push @decendents, @list; my @temp; for my $decendent (@list) { my $index = $self->{$decendent}{decendent}; push @temp, @{$self->{decendents}[$index]} if exists $self +->{decendents}[$index]; } @list = @temp; } return join ', ' , @decendents; } #### Example Usage: #### #!/usr/bin/perl -w use strict; use Isanchez; my $family_tree = Isanchez->new('file.dat'); print $family_tree->get_decendents('dog'), "\n"; # Where file.dat looks like __END__ 1 0 domestic_animal 2 1 dog 3 2 terrier 4 2 collie 5 3 fox_terrier
I was hoping one of you fine monks could show me a more elgeant/efficient/perlish solution.
Cheers - L~R
In reply to Code Review (recursive data structure) by Limbic~Region
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |