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:

#!/usr/bin/perl
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=shift;
    $obj->{NAME}=shift;
    $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??

Recommended Answers

All 2 Replies

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.

Thanks for the help, Rashakil Fol. :cool:

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.