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

Hello, Is it possible in Perl to redefine variable assignment? In Tcl I can rename the set command to say origSet and then define a new set which does something extra for global variables and then calls origSet.

I would like to do likewise in Perl, to wrap the assignment operator so that for global variables, I can do some extra work transparently to the user.

Thanks.

-William



Hi,

What I want to do is propagate global variable values between Perl and Tcl. I am successfully doing this in Tcl to Perl and seek the way to do this in Perl to Tcl.

I need to somehow trap on all global variable store commands and get the name of the variable and its value so that I can propagate the value to Tcl.

Seems to me like best would be a way to trap all calls to STORE without modifying the underlying Perl implementation directly. (i.e. user can pick whatever version of perl they want and the code works with it to trap calls to STORE).

Thanks.

-William

Replies are listed 'Best First'.
Re: How to wrap Perl assignment operator?
by Roy Johnson (Monsignor) on Oct 12, 2005 at 17:51 UTC
    You could tie the variables in question. You'd then write a STORE function that would behave in the new and wonderful way. I don't believe you can redefine the default STORE method.

    Caution: Contents may have been coded under pressure.
Re: How to wrap Perl assignment operator?
by Zaxo (Archbishop) on Oct 12, 2005 at 18:30 UTC

    My Tie::Constrained module sets up the sort of thing Roy Johnson mentioned for scalar variables. The pod for it shows several examples.

    There are examples on Perlmonks of wedging code into assignment with it. All these do their work even on code written without the need for their special properties in mind.

    After Compline,
    Zaxo

Re: How to wrap Perl assignment operator?
by chromatic (Archbishop) on Oct 12, 2005 at 18:07 UTC

    It's not easy without writing a source filter or XS code. What type of extra work do you have in mind?

      See my update to the question.
Re: How to wrap Perl assignment operator?
by davidrw (Prior) on Oct 12, 2005 at 17:51 UTC
    See overload for overloading perl operations for objects. Not sure if that fits your specific request though... But not sure if your approach is the best way -- are you sure you want transparently do stuff with something as basic as the '=' operator (could be extremely confusing)? Can you give a more detailed example of your intended use?