If I were to have a simple tied scalar class that increments every time it is read I could do that like this:
package Counter;
use strict;
use warnings;
sub TIESCALAR {
my $class = shift;
my $value = 0;
bless \$value, $class;
return \$value;
}
sub FETCH {
my $self = shift;
my $value = $$self;
$$self++;
return $value;
}
sub STORE {
my $self = shift;
$$self = shift;
}
1;
However to create a counter variable I have to use tie
. I could create one counter and export it. But what I really want to do is make it look OO. It seems that I could create a new
method like this:
sub new {
my $class = shift;
my $counter;
tie $counter, $class;
return $counter;
}
then in my main script get two counters by doing:
my $counter1 = Counter->new();
my $counter2 = Counter->new();
I am assuming this doesn't work because a tie doesn't survive a copy (I read that in the docs somewhere), is there simply no way to do this?
NB. I know it is only a matter of style, but it would LOOK more correct to the eye.