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

Dear Monks,

I want to write a -d: debugger that "knows" when variables are being modified.
I have seen the "watch" code in perl5db.pl, but I also want to catch cases when hashes/arrays/references get changed, so it doesn't help me.

How can it be done?
(Is it even possible to do it?)

Thanks.

Replies are listed 'Best First'.
Re: Knowing when variables change?
by davido (Cardinal) on Oct 24, 2004 at 16:37 UTC

    A not-so-difficult approach is to create a few tie classes, for arrays, scalars, hashes, and even filehandles if you wish. The classes should either log, or carp whenever a tied variable is modified.

    You won't be tieing every variable in your script (probably), but you can easily tie a few important (or suspect) ones.

    I posted a node with example code for tieing a scalar for the purpose of watching its access here: Re: Trapping acces to variables in-code. The example can easily be used as a starting point for hashes and arrays too.


    Dave

      I generally need to know about all my variables.
      How would tie affect the performance of my script?

        tie would affect performance of the script, especially if you tie every variable in it. Plus, there is no way to automatically tie every variable either. The problem is lexicals; you can't override my to coerce it into calling the tie constructor. So you'll have to manually tie every variable you're interested in. If you're interested in every variable, tie them all. But expect that to be a drag on the script's performance. The performance hit comes from the fact that variable access will now have all this extra work attached to it. You can't escape that.

        One strategy is to use a debug flag. If the script is invoked with the -tie flag (for example), your code would go ahead and tie every variable that you set up to do so. And if the script isn't invoked with the -tie flag, your script would skip the code that ties the variables you need to watch. That's just a matter of you coming up with the proper logic to make that happen.

        Is it possible that your problem has some other solution? What exactly are you really trying to do, that is requiring you to watch every single variable in the script?


        Dave