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
In reply to Using a tied scalar as an in memory file by duncs
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |