Cat class and dog class : Class Definition « Class « Perl






Cat class and dog class

 

package Cat;
sub new{
   my $class=shift;
   my $dptr={};
   bless($dptr, $class);
}
sub set_attributes{
   my $self= shift;
   $self->{"Name"}="Sylvester";
   $self->{"Owner"}="Mrs. Black";
   $self->{"Type"}="Siamese";
   $self->{"Sex"}="Male";
}
sub get_attributes{
   my $self = shift;
   while(($key,$value)=each( %$self)){
      print "$key is $value. \n";
   }
1;


# Dog.pm
package Dog;
sub new{             
    my $class=shift;
    my $dptr={};
    bless($dptr, $class);
}
sub set_attributes{
    my $self= shift;
    my($name, $owner, $breed)=@_;
    $self->{"Name"}="$name";
    $self->{"Owner"}="$owner";
    $self->{"Breed"}="$breed";
}
sub get_attributes{
    my $self = shift;
    print "All about $self->{Name}\n";
    while(($key,$value)= each( %$self)){
       print "$key is $value.\n";
    }
}
1;



#main.pl
#!/bin/perl
use Cat;
use Dog;

my $dogref = Dog->new;     
my $catref= Cat->new;

$dogref->set_attributes("Tom", "Jack", "Mutt");
$catref->set_attributes;   

$dogref->get_attributes;
$catref->get_attributes;

   
  








Related examples in the same category

1.A class is really just a package
2.A Perl class is a package containing a collection of variables and functions, called properties and methods.