in reply to more on tying localtime

This'll work for ya:

#!/usr/bin/perl -w use strict; package TieTimeArray; sub TIEARRAY { my $class = shift; my $self; $self->{ltime} = [localtime]; bless($self, $class); } sub FETCH { my ($self, $index) = @_; $self->{ltime}= [localtime]; +return $self->{ltime}->[$index] } sub FETCHSIZE { my $self = shift; return scalar @{$self->{ltime}} } package main; my @now; tie (@now, "TieTimeArray"); while (1) { print "@now\n"; sleep 1 }

The reason yours wasnt working before was because you didn't intitialize localtime in the constructor. However, your FETCH wouldnt work anyways because you were trying to return an array when a scalar was expected. FETCH returns the next element of the array, not the entire thing. Also, I stored your data in the object itself, which is handy just in case you need to reference it later. Finally, I threw in the 2 argument form of bless just in case that the class might need to be subclassed later. Its good practice to do anyways :)

Replies are listed 'Best First'.
Re: Re: more on tying localtime
by stefp (Vicar) on Sep 28, 2001 at 06:01 UTC
    This suffers of the very problem I described. It is evil to bind to an array when it is in effect a (here multibase) counter because it can wrap under you.

    -- stefp

      Yes, of course. That's why no one uses tied arrays :) He just wanted to know how to do one, so I gave him one way to solve the problem. I'm pretty confident that he won't be using it in regular practice, but its still a good way to learn about tied variables and classes.