This discussion motivated me to dig into tied scalars a little deeper. My goal was to create a tie by which any use of a given scalar would result in a write to a logfile, for debugging purposes. This is very quick and dirty, but here's what I've come up with. I would really appreciate comments that might lead me to improving it.

use strict; use warnings; package Trackit; my $varname; sub TIESCALAR { my $class = shift; $varname = shift; bless \my($self), $class; } sub STORE { ${ $_[0] } = $_[1]; document ( "STORE", $_[1] ); return ${ $_[0] }; } sub FETCH { my $self = shift; document( "FETCH", ${$self} ); return ${ $self } } sub DESTROY { my $self = shift; document ( "DESTROY", ${$self} ); } sub document { my ( $action, $value ) = @_; my $fh; open $fh, ">>log.txt" or die $!; print $fh "$varname => Action: $action, Value = $value\n"; close $fh; } # Begin main ---------------------------- package main; my $var; tie $var, "Trackit", '$var'; # Test our handywork... $var = 10; $var = $var + 10; open FH, "<log.txt" or die $!; while ( <FH> ) { print $_; } close FH;

Ok, here are the areas I see a need for improvement. First, it seems kludgy to have to pass as a string the name of the variable we're working with so that it can be printed to the logfile. Next, I haven't provided a way to user-specify the name of the logfile, but that's an easy fix. ...anything else?


Dave


In reply to Re: Debugging with tied variables by davido
in thread Debugging with tied variables by ysth

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.