如何在 Perl 中将 Graph 转换为 Graph::Easy?

How to convert Graph to Graph::Easy in Perl?

我使用 Graph 模块创建了一个图表。每个节点代表一条路径。例如,节点 1 是 /,节点 2 是 /a,节点 3 是 /a/b,那么节点 1 指向节点 2,节点 2 指向节点 3。如果节点是 link那么它只包含一个子节点。每个节点还包含一些属性。

作为调试目的的一部分,我试图以某种有意义的方式显示图形。我做了类似的事情:

foreach my $vertex (sort($graph->unique_vertices)) {
    my $type = $graph->get_vertex_attribute($vertex, 'type');
    if ($type eq "link") {
        my @target = $graph->successors($vertex);
        print($vertex." -> $target[0] ($type)\n");
    } else {
        print($vertex." ($type)\n");
    }
}

它创造了情侣:

/ -> /a
/ -> /c
/a -> /b

但我正在尝试创建一个更好的演示文稿来显示节点。一种方法是创建树视图(如 tree 的输出),但实现起来太困难了。我也尝试使用 Graph::Easy 模块,但我想不出一种方法来将我拥有的图形“转换”到该模块。有简单的方法吗?

#! /usr/bin/perl
use warnings;
use strict;

use Graph;
use Graph::Easy;

my $g = 'Graph'->new(directed => 1);
$g->add_edge('/', '/a');
$g->add_edge('/', '/c');
$g->add_edge('/a', '/b');

my $ge = 'Graph::Easy'->new;
for my $e ($g->edges) {
    $ge->add_edge(@$e);
}
print $ge->as_ascii;

输出:

+----+     +----+     +----+
| /  | --> | /a | --> | /b |
+----+     +----+     +----+
  |
  |
  v
+----+
| /c |
+----+

Graph(我是它的维护者)有一个非常好的 stringify 方法:

use Graph;
my $g = 'Graph'->new(directed => 1, edges => [[qw(/ /a)],[qw(/ /c)],[qw(/a /b)]]);
print $g, "\n";
# /-/a,/-/c,/a-/b

但是 GraphViz2(我是它的维护者)也很适合可视化,这对更复杂的图形很有用:

use Graph;
my $g = 'Graph'->new(directed => 1, edges => [[qw(/ /a)],[qw(/ /c)],[qw(/a /b)]]);
use GraphViz2;
GraphViz2->from_graph($g)->run(format => 'png', output_file => 'out.png');

输出: