vesii
vesii

Reputation: 3128

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

I have created a graph using the Graph module. Each node represents a path. For example node 1 is / and node 2 is /a and node 3 is /a/b then node 1 points to node 2 which points to node 3. If node is a link then it contains only one child node. Also each node contains some attributes.

As part of the debugging purpose, I'm trying to display the graph in some meaningful way. I did something like:

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");
    }
}

It creates couples:

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

But I'm trying to create a better presentation which shows the nodes. One way is to create a tree view (like the output of tree) but it was too difficult to achieve. Also I tried to use the Graph::Easy module but I could not figure a way to "convert" the graph I have to that module. Is there an easy way to do it?

Upvotes: 1

Views: 192

Answers (2)

Ed.
Ed.

Reputation: 2062

Graph (of which I'm maintainer) has a pretty good stringify method:

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

But GraphViz2 (of which I'm maintainer) is good for visualisation too, which will be useful for more complex graphs:

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');

Output: see output

Upvotes: 1

choroba
choroba

Reputation: 241828

#! /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;

Output:

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

Upvotes: 3

Related Questions