duncs has asked for the wisdom of the Perl Monks concerning the following question:
I use Log::Log4perl in a daemon for logging purposes, but that daemon runs other code via system's and qx//'s, so to capture output I redirect their output to a different file.
However, I thought, it would be good to get their STDxxx output into Log4perl too. Looking around it doesn't seem possible, but then I noticed in the 5.8.x open() perldoc you can open an in-memory IO handle on a scalar variable.
Great, I thought, I can tie a scalar to the log4perl warn and info functions and then use open on that scalar to reopen the STDxxx filehandles. Here is the code I have in my tie module:
my %function_for; my %scalar_ref_for; sub TIESCALAR { my ( $class, $function ) = @_; if ( ref $function ne 'CODE' ) { croak('Argument to tie must be a code reference'); } my $self = bless \do { my $anon_scalar }, $class; $function_for{ ident $self } = $function; $scalar_ref_for{ ident $self } = q{}; return $self; } sub STORE { my ( $self, @args ) = @_; $function_for{ ident $self }->(@args); } sub FETCH { my( $self ) = @_; return $scalar_ref_for{ ident $self }; }
Running some tests it works fine with:
my $tied_variable; tie $tied_variable, 'Tie::Scalar::Function' => sub { ok( defined $_[0], "got something + -> $_[0]" ) }; $tied_variable = "assignment";
However, using open against it doesn't work at all:
my $tied_variable; tie $tied_variable, 'Tie::Scalar::Function' => sub { ok( defined $_[0], "got something + -> $_[0]" ) }; warn 'here1:',$tied_variable; open(my $fh, '>', \$tied_variable); print {$fh} 'this is a test'; warn 'here2:',$tied_variable;
$tied_variable does get set by the print on the filehandle but STORE is not called via the tie - somehow its being circumvented.
What am I missing here? I am doing something wrong but I cannot see it...
Thanks
Duncs
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Using a tied scalar as an in memory file
by almut (Canon) on Feb 19, 2009 at 18:46 UTC | |
by ikegami (Patriarch) on Feb 19, 2009 at 18:55 UTC | |
|
Re: Using a tied scalar as an in memory file
by ELISHEVA (Prior) on Feb 20, 2009 at 06:37 UTC | |
by ikegami (Patriarch) on Feb 20, 2009 at 14:56 UTC | |
by ELISHEVA (Prior) on Feb 21, 2009 at 19:50 UTC | |
by ikegami (Patriarch) on Feb 21, 2009 at 21:05 UTC | |
by ELISHEVA (Prior) on Feb 22, 2009 at 13:12 UTC | |
| |
by duncs (Beadle) on Feb 20, 2009 at 09:24 UTC | |
|
Re: Using a tied scalar as an in memory file
by ikegami (Patriarch) on Feb 19, 2009 at 17:49 UTC |