in reply to Re^4: Global or not global
in thread Global or not global
Do you have some kind of resilence if STDLOG is not set up from the using script?
As I said, STDERR (via Carp croak() and cluck() ) mostly serves my purposes, but for sake of demonstration:
Given Logndebug.pm:
package Logndebug; use strict; use warnings; use Exporter; our @ISA = qw[ Exporter ]; our @EXPORT = qw[ LOG DEBUG logging ]; sub LOG { return unless fileno( *STDLOG ); print STDLOG @_; } sub DEBUG { return unless fileno( *STDDBG ); print STDDBG @_; } sub logging { my( $logging, $debugging ) = @_; *STDLOG = *{ $logging } if defined $logging and fileno( $loggi +ng ); *STDDBG = *{ $debugging } if defined $debugging and fileno( $debug +ging ); } 1;
And SillyVec3D.pm:
package SillyVec3D; use strict; use warnings; use Logndebug; sub new { my $class = shift; my $self = bless { @_ }, $class; for my $attr ( keys %{ $self } ) { no strict 'refs'; eval qq[ *{ $attr } = sub { LOG( "$attr called with [\@_]" ); my \$self = shift; DEBUG( "$attr set to: ", \$self->{ $attr } = shift ) i +f \@_; \$self->{ $attr }; } ]; } return $self; } 1;
And t-SillyVec3D.pl:
#! perl -slw use strict; use SillyVec3D; our( $LOG, $DBG ); SillyVec3D::logging( $LOG ? *STDERR : undef, $DBG ? *STDERR : undef, ); my $o = SillyVec3D->new( X => 1, Y => 2, Z => 3 ); print $o->X, $o->Y, $o->Z; $o->X( 4 ); $o->Y( 5 ); $o->Z( 6 ); print $o->X, $o->Y, $o->Z;
In use:
C:\test>t-SillyVec3D 123 456 C:\test>t-SillyVec3D -LOG X called with [SillyVec3D=HASH(0x32cf38)] Y called with [SillyVec3D=HASH(0x32cf38)] Z called with [SillyVec3D=HASH(0x32cf38)] 123 X called with [SillyVec3D=HASH(0x32cf38) 4] Y called with [SillyVec3D=HASH(0x32cf38) 5] Z called with [SillyVec3D=HASH(0x32cf38) 6] X called with [SillyVec3D=HASH(0x32cf38)] Y called with [SillyVec3D=HASH(0x32cf38)] Z called with [SillyVec3D=HASH(0x32cf38)] 456 C:\test>t-SillyVec3D -DBG 123 X set to: 4 Y set to: 5 Z set to: 6 456 C:\test>t-SillyVec3D -LOG -DBG X called with [SillyVec3D=HASH(0x8cf48)] Y called with [SillyVec3D=HASH(0x8cf48)] Z called with [SillyVec3D=HASH(0x8cf48)] 123 X called with [SillyVec3D=HASH(0x8cf48) 4] X set to: 4 Y called with [SillyVec3D=HASH(0x8cf48) 5] Y set to: 5 Z called with [SillyVec3D=HASH(0x8cf48) 6] Z set to: 6 X called with [SillyVec3D=HASH(0x8cf48)] Y called with [SillyVec3D=HASH(0x8cf48)] Z called with [SillyVec3D=HASH(0x8cf48)] 456
You get logging and tracing embedded in the package, with minimal impact when turned off, and controlled from the calling script that can send the output wherever it choses with a single call on a package by package basis.
And if you set logging/debug on by passing in tied filehandles, they can add whatever boilerplate you desire.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^6: Global or not global
by McA (Priest) on Jul 03, 2012 at 19:53 UTC |