Is there any class pointers in Perl in order to access member variables and functions?

Viewed 128

I'm looking to build a Node class in Perl (using the keyword 'package'), but I'm not sure how to create a pointer to class variable like in C++.

In C++, you have:

class Node
{
public:
    int key;
    Node* left;
    Node* right;

    Node(int _key)
    {
        key = _key;
        left = NULL;
        right = NULL;
    }
};

In Perl:

package Node;
sub Node
{
    my $class = shift;

    my $key;
    Node* left;        # Of course, this will not work
    Node* right;
}

Is there any way I could make a pointer to class variable in Perl? Or if it's not possible, any suggestions on Perl modules that could do what I want to do?

2 Answers
package Node;

use strict;
use warnings qw( all );

use Carp qw( croak );

sub new  {
   my ($class, %args) = @_;

   croak("key is required") if !exists($args{key});

   my $self = bless({}, $class);

   $self->{ key   } = $args{ key   };
   $self->{ left  } = $args{ left  };
   $self->{ right } = $args{ right };

   return $self;
}

sub key   { my $self = shift; $self->{ key   } = shift if @_; $self->{ key   } }
sub left  { my $self = shift; $self->{ left  } = shift if @_; $self->{ left  } }
sub right { my $self = shift; $self->{ right } = shift if @_; $self->{ right } }

1;

or

package Node;

use strict;
use warnings qw( all );

use Moo;

use namespace::clean;

has key   => ( is => 'rw', required => 1 );
has left  => ( is => 'rw' );
has right => ( is => 'rw' );

1;

Usage:

my $node = Node->new(
   key   => $key,
   left  => $left,    # Optional. Defaults to undef.
   right => $right,   # Optional. Defaults to undef.
);

Actually if you want to use OOP in Perl you should check out existing frameworks like Moose or do it yourself using bless. An example:

package Node;

sub new {
  my ($class, $key) = @_;
  bless { key => $key }, $class;
}

my $node = Node->new();

Later on, you can add the "pointers" to the "object" by adding references to the nodes to the hash inside node.

Related