Beefy Boxes and Bandwidth Generously Provided by pair Networks Joe
go ahead... be a heretic
 
PerlMonks  

Re: OOP/Linked List Question

by RazorbladeBidet (Friar)
on Feb 07, 2005 at 16:47 UTC ( #428737=note: print w/ replies, xml ) Need Help??


in reply to OOP/Linked List Question

Here's an exercise in fun OOP that's fairly unnecessary, but just in case you REALLY want objects :)

package LinkedList; use strict; my $HEAD_NODE = undef; # use a global var to get the head node sub new { my $this = shift; my $class = ref($this) || $this; my $self = {}; $self->{_ID} = shift || "Id"; $self->{_NAME} = shift || "Default"; $HEAD_NODE = $self unless defined $HEAD_NODE; $self->{_NEXT} = $HEAD_NODE; bless $self, $class; } sub name { my $self = shift; $self->{_NAME} = shift if @_; return $self->{_NAME}; } sub id { my $self = shift; $self->{_ID} = shift if @_; return $self->{_ID}; } # this really should handle references to objects, and not # the object itself... sub add_node { my $self = shift; my $node_to_add = shift; $self->{_NEXT} = $node_to_add; } # this really should handle references to objects, and not # the object itself... sub next { my $self = shift; return $self->{_NEXT}; } # may not be necessary DESTROY { my $self = shift; $self->{_NEXT} = undef; } 1; ---- #!/usr/bin/perl use strict; use LinkedList; my $first_node = LinkedList->new( 1, "data" ); my $second_node = LinkedList->new( 2, "more data"); my $third_node = LinkedList->new(3, "even more data"); $first_node->add_node( $second_node ); $second_node->add_node( $third_node ); my $node = $first_node; for ( my $i = 0; $i < 100; $i++ ) { print $node->id." ".$node->name."\n"; $i++; $node = $node->next; }
Update: A note from perlobj:
In the meantime, the best solution is to create a non-
recursive container class that holds a pointer to the self-
referential data structure. Define a DESTROY method for 
the containing object's class that manually breaks the 
circularities in the self-referential structure.
So maybe instead, call the above package (class) LinkedListNode and have a container LinkedList, just to be safe.


Comment on Re: OOP/Linked List Question
Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://428737]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others having an uproarious good time at the Monastery: (24)
As of 2014-04-16 13:43 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    April first is:







    Results (427 votes), past polls