Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot
 
PerlMonks  

How to tie variables to objects

by perldeveloper (Scribe)
on Jul 30, 2004 at 17:11 UTC ( [id://378751]=perlquestion: print w/replies, xml ) Need Help??

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.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://378751]
Approved by calin
Front-paged by broquaint
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (4)
As of 2024-04-15 02:34 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found