Return to Snippet

Revision: 21083
at December 2, 2009 21:49 by freephys


Initial Code
##1
#Network class relies on two other classes
#1.Node class
#2.Link, whose objects represent a single unidirectional link to another Node
##
package Network;
use strict;
sub new
{
my ($class) = @_;
bless { _nodes => [] }, $class;
}
sub node
{
my ($self, $index) = @_;
return $self->{_nodes}->[$index];
}
sub add_node
{
my ($self) = @_;
push @{$self->{_nodes}}, Node->new();
}
##
#providing the Network class with a destructor that explicitly removes the Links
#between Nodes at the appropriate time
##
sub DESTROY
{
my ($self) = @_;
foreach my $node ( @{$self->{_nodes}} )
{
$node->delete_links();
}
}

##2
# Node class, which Network class is relied on
##
package Node;
use strict;
{
my $_nodecount=0;
sub _nextid { return ++$_nodecount }
}
sub new
{
my ($class) = @_;
bless { _id => _nextid(), _outlinks => [] }, $class;
}
sub add_link_to
{
my ($self, $target) = @_;
push @{$self->{_outlinks}}, Link->new($target)
}
##
#in order to remove circular data structure
##
sub delete_links
{
my ($self) = @_;
delete $self->{_outlinks};
}
##3
#Link class which Node class is relied on
##
package Link;
use strict;
{
my $_linkcount=0;
sub _nextid { return ++$_linkcount }
}
sub new
{
my ($class) = @_;
bless{_id=> _nextid(),
_to=> $_[1],
}, $class;
}

Initial URL

                                

Initial Description

                                

Initial Title
Example of circular data structure : Network class

Initial Tags
data

Initial Language
Perl