Here's a different approach: adding wrappers to the standard tied routines instead of redefining them:
# usage: tie $var, 'Tie::Scalar::Log', # init value (may be undef), # logfile (string), # varname (string), # events (array or undef); ## Tie::Scalar::Log.pm package Tie::Scalar::Log; use Hook::LexWrap; use IO::File; use Carp; require Tie::Scalar; our @ISA = qw/Tie::StdScalar/; my %LOG_IT; wrap Tie::StdScalar::TIESCALAR, post => sub { my $self = $_[-1]; my ($logfile,$name,$events) = @_; $logfile ||= ''; my $log = IO::File->new($logfile,'>>'); if ($log) { $LOG_IT{$self} = {name => $name, log => $log}; $events ||= []; $events = [qw/TIESCALAR FETCH STORE DESTROY/] if grep /all/i, @$events or !@$events; $LOG_IT{$self}{uc($_)} = 1 for @$events; $self->logit("TIESCALAR => $logfile") if $LOG_IT{$self}{TIESCALA +R}; } else { carp "logfile <$logfile> couldn't be created: variable not tied" +; $_[-1] = undef; } }, pre => sub { carp q|Wrong number of arguments to tie()| and $_[-1] = undef unless @_ == 6 }; wrap Tie::StdScalar::FETCH, post => sub {$_[0]->logit("FETCH => $_[-1]") if $LOG_IT{$_[0]}{FETCH +}}; wrap Tie::StdScalar::STORE, post => sub {$_[0]->logit("STORE => $_[-1]") if $LOG_IT{$_[0]}{STORE +}}; wrap Tie::StdScalar::DESTROY, post => sub {$_[0]->logit("DESTROY") if $LOG_IT{$_[0]}{DESTROY}}; sub logit { my ($self, $msg) = @_; my $name = $LOG_IT{$self}{name}; my ($pkg,$file,$line) = caller(1); print {$LOG_IT{$self}{log}} "$name => $msg ", "\t<at $file line $line>\n" } 1;
In reply to Re: Scalars tied to logfiles
by Anonymous Monk
in thread Scalars tied to logfiles
by davido
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |