in reply to Passing List::Compare a list of arrays
G'day AWallBuilder,
It would have been useful if you'd supplied some indication of the data you're working with: replies along the lines of "I don't really know what you're doing" tend to bear this out.
I was having similar problems myself. I also didn't understand your syntax issue: List::Compare seems well documented and, to be honest, two of the (only) five lines in its SYNOPSIS should have got you substantially further than what you've posted.
Anyway, I hadn't used List::Compare previously so I was curious. Here's what I came up with:
#!/usr/bin/env perl -l use strict; use warnings; use List::Compare; my %tree_path_for; my %is_known_node; my @nodes; while (<DATA>) { my ($node, $parent) = split; ++$is_known_node{$node}; $tree_path_for{$node} = [$node => $parent eq 'root' ? () : \$tree_path_for{$parent}] +; } for (@ARGV) { if ($is_known_node{$_}) { push @nodes => $_; } else { print "Unknown node: $_"; } } if (! @nodes) { print "No valid nodes to process!"; } else { print "Nodes for this run: @nodes"; if (@nodes == 1) { print "Need at least two nodes to process!"; } else { my @commons = List::Compare::->new( map { [ flatten_nested_AoA($tree_path_for{$_}) ] } @nodes )->get_intersection; if (@commons) { print "Lowest common ancestor: ", $commons[-1]; } else { print "No common ancestor!"; } } } sub flatten_nested_AoA { map { ref $_ ? flatten_nested_AoA($$_) : $_ } @{+shift} } # Example ancestor trees # # _A_ W # / \ | # B __C__ X # / | \ / \ # D E F Y Z # / \ # G H # Data: node parent # __DATA__ G E D C C A A root E C H E Y X F C X W Z X W root B A
Here's a few sample runs:
$ pm_find_common_ancestors.pl D E F Nodes for this run: D E F Lowest common ancestor: C
$ pm_find_common_ancestors.pl X Y N O P Unknown node: N Unknown node: O Unknown node: P Nodes for this run: X Y Lowest common ancestor: X
pm_find_common_ancestors.pl X N O P Unknown node: N Unknown node: O Unknown node: P Nodes for this run: X Need at least two nodes to process!
$ pm_find_common_ancestors.pl G H X Y Nodes for this run: G H X Y No common ancestor!
$ pm_find_common_ancestors.pl N O P Unknown node: N Unknown node: O Unknown node: P No valid nodes to process!
Maybe you can adapt this to your requirements.
-- Ken
|
|---|