hi.
we currently have a school assignment on PERL that goes something like the following:
package A;
use base qw(C);
sub increment{
my $self = shift;
return $self->{count}++;
}
package B;
use base qw(C);
sub increment{
my $self = shift;
return $self->{count}++;
}
packages A and B are used in the main program which looks like this:
#!/usr/bin/perl -w
use strict;
use A;
use B;
my $A1 = A->new();
print $A1->increment(); # output is '0'
my $A2 = A->new();
print $A2->increment(); # output is '1'
my $B1 = B->new();
print $B1->increment(); # output is '0'
my $B2 = B->new();
print $B2->increment(); # output is '1'
our task is to implement package C. in my implementation, i made count to be a class variable, like:
package C;
my $this;
$this->{count} = 0;
sub new{
$C = shift;
bless $this, $C;
return $this;
}
1;
however, my problem now is that all objects (A1, A2, B1, B2) refer to the same count variable. thus, instead of outputting 0101, i get 0123. i guess this is because packages A and B both use C, where the count is a class variable.
we cannot change packages A or B, or even the main .pl file. we can only create package C. my implementation works only in that it outputs 0123, not 0101.
would anyone happen to know how to solve this?
we currently have a school assignment on PERL that goes something like the following:
package A;
use base qw(C);
sub increment{
my $self = shift;
return $self->{count}++;
}
package B;
use base qw(C);
sub increment{
my $self = shift;
return $self->{count}++;
}
packages A and B are used in the main program which looks like this:
#!/usr/bin/perl -w
use strict;
use A;
use B;
my $A1 = A->new();
print $A1->increment(); # output is '0'
my $A2 = A->new();
print $A2->increment(); # output is '1'
my $B1 = B->new();
print $B1->increment(); # output is '0'
my $B2 = B->new();
print $B2->increment(); # output is '1'
our task is to implement package C. in my implementation, i made count to be a class variable, like:
package C;
my $this;
$this->{count} = 0;
sub new{
$C = shift;
bless $this, $C;
return $this;
}
1;
however, my problem now is that all objects (A1, A2, B1, B2) refer to the same count variable. thus, instead of outputting 0101, i get 0123. i guess this is because packages A and B both use C, where the count is a class variable.
we cannot change packages A or B, or even the main .pl file. we can only create package C. my implementation works only in that it outputs 0123, not 0101.
would anyone happen to know how to solve this?