http://qs321.pair.com?node_id=378751

perldeveloper has asked for the wisdom of the Perl Monks concerning the following question:

Hi, I've asked a similar question an hour ago in the ChatterBox, but I need more room to really explain it: Is there a way (a cpan module using XS, or anything) to tie a variable to an existing instance of an object, rather than specify the classname and its constructor parameters?

Basically, assuming a scalar, you'd have a tying-class (say TyingClass) (the class defining sub TIESCALAR) and a scalar variable (say $variable). With these two, you'd normally write something like:
tie $variable, 'TyingClass', @optionalConstructorParameters
Then, tied $variable would return the instance (created running TyingClass->TIESCALAR(@optionalConstructorParameters)).

But say I created my own instance of the TyingClass, named $tyingInstance (passing any set of constructor parameters). And then, I've changed the instance calling a stateful method on $tyingInstance (a method which depends on the state of its object), and this method actually changed the $tyingInstance object, in a way that cannot be reproduced by its constructor. How can one (if they can) tie my $variable to $tyingInstance, assuming TyingClass can be any Perl class, not specifically designed for this purpose.

Maybe there's a good reason why tying is done only in this way, so if there is one, I'd appreciate if someone took the time to explain it. Thanks.

Replies are listed 'Best First'.
Re: How to tie variables to objects (roll)
by tye (Sage) on Jul 30, 2004 at 17:22 UTC

    It is the way it is. That was how the author of the 'tie' feature conceived of it being used.

    (for the third time) It isn't hard to tie to an existing object. For example:

    package MyClass; #... sub TieArray { my( $me, $av )= @_; tie @$av, ref($me), $me; } sub Class::TIEARRAY { return $_[1]; } package main; my $obj= MyClass->new( ... ); my @array; $obj->TieArray(\@array);

    Untested and just One Way To Do It.

    - tye        

Re: How to tie variables to objects
by ysth (Canon) on Jul 30, 2004 at 17:29 UTC
    This is easy to do yourself; if you'd prefer a module to make it even easier, there is Tie::Restore.