Monday, January 20, 2014

OOP and Perl / or how to get crazy when you are still young? Part 4

Today I'm gonna write a little bit about static variables. What are they?
This are variables (in OOP: properties) that are the same in the all instances of the class.
What does this mean?
The easiest way to understand it is to get an example. So let's write some code!
package Creature2;
#A Creature Class
#Creature2.pm
use warnings;
use strict;

my $numberOfCreatures = 0; #This is static! All of the creatures use it.

sub new {
 my $class = shift;
    my $self = {};
    bless($self, $class);
    
    $self->set_kind("Dog");
    $numberOfCreatures++;
    return $self;
}

sub get_kind {
 my $self = shift;
 return $self->{kind}
}

sub set_kind {
 my $self = shift;
 print "Setting the kind to '", $_[0], "'\n";
 $self->{kind} = $_[0];
}

sub get_number {
 print "Number ot the creatures is: ", $numberOfCreatures, "\n";
}

sub DESTROY {
 #This is the destructor. It exists even if you do not define it and it has been executed every time when the object disapears from the scope of view (resp. doesn't exist any more) or at the end of the program.
 my $self = shift;
 $numberOfCreatures--;
 print "Obj. ", $self->get_kind, " destroyed.\n";
 print "The world is epmty!\n" if $numberOfCreatures == 0;
}

1;
And our program:
#!/usr/bin/perl -w
#staticTest.pl
#I use -w just because of the habbit.
use warnings; #This is the same as -w
#But when you use -W (capital letter W) you get advanced warning messages. (more detailed msgs)
use strict;
use Creature2;

my $doggy = Creature2->new();

$doggy->get_number;

{
 #This is the scope of view of the cat.
 my $cat = Creature2->new();
 $cat->set_kind('Cat');
 $doggy->get_number;
 #As you cann see, I'm calling only $doggy->get_number all the time. But to see that the $numberOfCreatures in $cat is the same I'll print it again:
 print "Again: \n";
 $cat->get_number;
}

#Here the cat doesn't exist any more.
$doggy->get_number;
And this is our output:
> ./staticTest.pl 
Setting the kind to 'Dog'
Number ot the creatures is: 1
Setting the kind to 'Dog'
Setting the kind to 'Cat'
Number ot the creatures is: 2
Again: 
Number ot the creatures is: 2
Obj. Cat destroyed.
Number ot the creatures is: 1
Obj. Dog destroyed.
The world is epmty!
Till the next time and good luck!