Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

Re: monitor STDOUT in scalar

by btrott (Parson)
on Aug 10, 2000 at 06:32 UTC ( [id://27235]=note: print w/replies, xml ) Need Help??


in reply to monitor STDOUT in scalar

You should be able to inherit from Tie::Handle (part of the standard distribution) and override any methods you wish to define yourself:
package MySTDOUT; use Tie::Handle; @ISA = qw/Tie::Handle/; sub TIEHANDLE { my $class = shift; bless {}, $class; } package main; tie *STDOUT, 'MySTDOUT';
For example, maybe you want to trap every call to STDOUT and prefix each argument with a string of your own:
package MySTDOUT; use Tie::Handle; @ISA = qw/Tie::Handle/; sub TIEHANDLE { my $class = shift; bless {}, $class; } sub PRINT { my $self = shift; my $caller = caller; print STDERR map "$caller: $_", @_; } package main; tie *STDOUT, 'MySTDOUT'; print "Foo";
Prints
main: Foo
Take a look at the Apache module and Apache::Filter for some examples of tying STDOUT.

Replies are listed 'Best First'.
RE: Re: monitor STDOUT in scalar
by Adam (Vicar) on Aug 10, 2000 at 20:14 UTC
    That is very cool! It also answers a question I asked some time ago, about Line Numbers. You could use this to put line numbers in your debug log:
    package MyDEBUGLOG; use Tie::Handle; @ISA = qw/Tie::Handle/; sub TIEHANDLE { my $class = shift; bless {}, $class; } { my $line = 0; sub PRINT { my $self = shift; ++$line; print DEBUGLOG map "$line: $_", @_; } } package main; tie *DEBUGLOG, 'MyDEBUGLOG'; print DEBUGLOG "Foo";
    Or so I would suspect. Very cool.
      Well, not quite, because DEBUGLOG isn't opened for writing, for one thing, and for another, it's tied in a different package than when you're actually writing to it (main vs. MyDEBUGLOG).

      And even if you do work out those issues, I think you'll have a problem with "Deep Recursion". You're writing to a tied filehandle, which invokes the PRINT method on your tied object, which... writes to the same tied filehandle. Hence recursion.

      Check out my new Snippet, Filehandle Filter. With that you could do this:

      use Filter::Handle; local *DEBUG open DEBUG, ">debuglog" or die $!; my $f = Filter::Handle->new(\*DEBUG); print DEBUG "Foo"; print DEBUG "Bar";
        Cool, Thanks...

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://27235]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others having an uproarious good time at the Monastery: (4)
As of 2024-04-18 18:43 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found