Example of circular data structure : Network class


/ Published in: Perl
Save to your folder(s)



Copy this code and paste it in your HTML
  1. ##1
  2. #Network class relies on two other classes
  3. #1.Node class
  4. #2.Link, whose objects represent a single unidirectional link to another Node
  5. ##
  6. package Network;
  7. use strict;
  8. sub new
  9. {
  10. my ($class) = @_;
  11. bless { _nodes => [] }, $class;
  12. }
  13. sub node
  14. {
  15. my ($self, $index) = @_;
  16. return $self->{_nodes}->[$index];
  17. }
  18. sub add_node
  19. {
  20. my ($self) = @_;
  21. push @{$self->{_nodes}}, Node->new();
  22. }
  23. ##
  24. #providing the Network class with a destructor that explicitly removes the Links
  25. #between Nodes at the appropriate time
  26. ##
  27. sub DESTROY
  28. {
  29. my ($self) = @_;
  30. foreach my $node ( @{$self->{_nodes}} )
  31. {
  32. $node->delete_links();
  33. }
  34. }
  35.  
  36. ##2
  37. # Node class, which Network class is relied on
  38. ##
  39. package Node;
  40. use strict;
  41. {
  42. my $_nodecount=0;
  43. sub _nextid { return ++$_nodecount }
  44. }
  45. sub new
  46. {
  47. my ($class) = @_;
  48. bless { _id => _nextid(), _outlinks => [] }, $class;
  49. }
  50. sub add_link_to
  51. {
  52. my ($self, $target) = @_;
  53. push @{$self->{_outlinks}}, Link->new($target)
  54. }
  55. ##
  56. #in order to remove circular data structure
  57. ##
  58. sub delete_links
  59. {
  60. my ($self) = @_;
  61. delete $self->{_outlinks};
  62. }
  63. ##3
  64. #Link class which Node class is relied on
  65. ##
  66. package Link;
  67. use strict;
  68. {
  69. my $_linkcount=0;
  70. sub _nextid { return ++$_linkcount }
  71. }
  72. sub new
  73. {
  74. my ($class) = @_;
  75. bless{_id=> _nextid(),
  76. _to=> $_[1],
  77. }, $class;
  78. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.