PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, June 27, 2022

[FIXED] How to convert Graph to Graph::Easy in Perl?

 June 27, 2022     graph, perl     No comments   

Issue

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?


Solution

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


Answered By - choroba
Answer Checked By - Katrina (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing