On Fri, Jul 20, 2001 at 12:36:23PM -0400, Kort, Eric wrote:
> Damian Conway's book OO Perl, in discussing ties, suggests that the
> following will create a scalar that increments by one everytime its value is
> accessed:
> 
> package Incr;
> 
> sub TIESCALAR
> {
>   my ($class) = @_;
>   my $value = 0;
>   bless \$value, $class;
> }
> 
> sub FETCH
> {
>   my ($value) = @_;
>   return ++${$value};
> }
> 
> But, when I do the following:
> 
> #!perl
> 
> use lib "C:\\Perl";
> use Incr;
> 
> tie $foo, "Incr";
> print "$foo\n";
> print "$foo\n";
> print "$foo\n";
> print "$foo\n";
> print "$foo\n";
> 
> exit;
> 
> I get:
> 2
> 4
> 6
> 8
> 10
> 
> Presumable because FETCH calls FETCH itself to do the incrementing,
> resulting in a double increment!  How can one get a single increment with a
> tie?

In perl5.005 and 5.6.0, I get the correct behavior, but in perl5.6.1, FETCH
*is* called twice for each fetch.  Stick a warn "FETCH\n"; at the top of
the FETCH sub, and you get:

FETCH
FETCH
2
FETCH
FETCH
4
FETCH
FETCH
6
FETCH
FETCH
8
FETCH
FETCH
10


Fortunately, the latest development release also gives the correct
behavior, so this is a bug that was introduced in 5.6.1 and has already
been fixed for the next release.


Ronald

Reply via email to