'How to look for a node by id in the Perl Graph.pm module?
I'm trying to use the Graph.pm module but all the examples I saw are keeping simple basic scalars as nodes. I'm trying to keep instances of three different classes as nodes in that graph. Consider:
sub new {
my ($class,$node_name) = @_;
my $self = {
"name" => $node_name,
# More fields
};
bless $self, $class;
return $self;
}
Now I can do something like:
$g->add_vertex(new DNode("/"));
where DNode is the constructor of one of the three classes. But how can I can look for that node? For example, I have:
$g->add_vertex(new DNode("/"));
$g->add_vertex(new DNode("/a"));
$g->add_vertex(new DNode("/a/b"));
my $node = $g->get_vertex("/a/b");
There is no get_vertex. I thought that add_vertex_by_id can be helpful here:
$g->add_vertex_by_id(new DNode("/"),"/");
$g->add_vertex_by_id(new DNode("/a"),"/a");
$g->add_vertex_by_id(new DNode("/a/b"),"/a/b");
But there is no get_vertex_by_id method. How can I do the lookup?
Solution 1:[1]
It's not 100% clear what you're really trying to achieve. I can try to explain the things you did ask about (I'm the module's current maintainer).
The Graph module is about things, and connections between things. The usual approach, which I think will work for you here, is to identify "things" (vertices) by string names, such as "/" or "/a", and set an attribute (e.g. object) as the Perl object. You can instead have the vertices identified by actual Perl objects, using refvertexed.
Once you've added a vertex, like this:
$g = Graph->new;
$g->set_vertex_attribute('/a', object => $node_class->new('/a')); # no need to separately add vertex
You can look it up:
$bool = $g->has_vertex('/a');
$obj = $g->get_vertex_attribute('/a', 'object'); # safely returns undef if no such vertex, or attribute not set
The by_id methods are part of Multiedges, Multivertices, Multigraphs, where you'd have several (or "multi") "aspects" of the same vertex, each identified by an ID. I don't think that's what you want here.
If this doesn't solve your problem, you'd need to explain your problem more/better :-)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ed. |
