Hi all

Sorry, I didn't know where to post my perl programming question.

I'm having a problem creating objects in perl. I found a piece of code on the internet, that gives an example of classes and objects in perl. I modified it a little bit, and now have this code:

use strict;

my $dog1 = new("Dog","Shane","white");
my $dog2 = new("Dog","Tom","brown");

print "I am a dog called ". $dog1->getName()." and I am " . $dog1->getColour() . "\n";
print "I am a dog called ". $dog2->getName()." and I am " . $dog2->getColour() . "\n";

sub new {
  my $class = shift;   # Determine the class for the oject to create
  my $name=shift;
  my $colour=shift;
  my $obj = {};        # Instantiate a generic empty object
  bless $obj, $class;  # 'bless' this new generic object into the desired class
  $obj->_init($name,$colour);     # Run the '_init()' sub for this class of object
  return $obj;         # Return our newly blessed and loaded object

package Dog;

my $obj;

sub _init {
    $obj->{COLOUR} = shift;
sub getName{
  return $obj->{NAME};
sub getColour{
  return $obj->{COLOUR};

The problem is that whenever I create an object, it sort of overwrites the old object. So the above code gives the output:

"I am a dog called Tom and I am brown."
"I am a dog called Tom and I am brown."

What am I doing wrong??

You shouldn't have $Dog::obj be a package global there. Make it a local variable in _init.

Your getColour, getName subroutines are returning the attributes of whatever hash reference is contained in $Dog::obj. This happens to point to the hash of whatever Dog was initialized most recently. They should return the attributes of their passed argument, @_[0], instead.

Perl packages do not work the same way as C++ classes.

This article has been dead for over six months. Start a new discussion instead.