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
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);
    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";

 #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;
 print "Obj. ", $self->get_kind, " destroyed.\n";
 print "The world is epmty!\n" if $numberOfCreatures == 0;

And our program:
#!/usr/bin/perl -w
#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();


 #This is the scope of view of the cat.
 my $cat = Creature2->new();
 #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";

#Here the cat doesn't exist any more.
And this is our output:
> ./ 
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
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!