in reply to Re(2): STDOUT::Capture - manipulate STDOUT
in thread STDOUT::Capture - manipulate STDOUT

My thoughts were to just make MyCapture a subclass of Tie::Handle::Scalar that registers callbacks. Here's an example MyCapture.pm that is similar to your STDOUT::Capture module. You could go ahead and provide a wrapper module that hardcodes the desired callbacks as you do, or hardcode them directly in this subclass.

## -- MyCapture.pm -- ## package MyCapture; use Tie::Handle::Scalar; our @ISA = qw/Tie::Handle::Scalar/; my %callbacks; sub import { my $self = shift; %callbacks = @_; } sub PRINT { my $self = shift; my $input = join '', @_; if(exists $callbacks{on_print}){ $callbacks{on_print}->(\$input); } $self->SUPER::PRINT($input); } sub DESTROY { my $self = shift; if(exists $callbacks{on_finish}){ $callbacks{on_finish}->($self->{data}); } print ${$self->{data}}; } 1; __END__ ## -- test.pl -- ## #!/usr/bin/perl -w use strict; use CGI qw(:standard); use MyCapture on_finish => \&on_finish, on_print => sub{${$_[0]} =~ s/\bcgi\b/CGI/g}; sub on_finish { my $input = shift; $$input =~ s{(</head>)} {<link rel="stylesheet" type="text/css" href="/css/style.css" />\n +$1}i; } tie *STDOUT, 'MyCapture'; print header; print start_html(-title => 'Cool cgi program'); print h1('Welcome to my cool cgi!'); print p('This is just a test page.'); print end_html; untie *STDOUT; __END__

Replies are listed 'Best First'.
Re(4): STDOUT::Capture - manipulate STDOUT
by Dog and Pony (Priest) on Jun 10, 2002 at 07:04 UTC
    To have it the way I wanted it, it still takes one extra module between these two, where the callbacks and such is set up (for reasons mentioned above). But yes, I understood that a subclass would work too, I was just fiddling around to get it working and see what could be done. Moreover, I never got DESTROY to work in my version (thus the END blocks), maybe it is time to revisit that.

    What I want is to have little to none impact on my existing programs, codewise, not even a callback copied into them (not to mention the potential maintenance nightmare). :)

    Anyhow, now I think which approach should be taken, depends on if one foresee any added functionality in the future that could benefit from the extra functionality in Tie::Handle::Scalar, or not. Can't come up with anything at the moment, but there is probably something.

    Thanks for the example... I have some more zzz to catch, but I'll look more closely later. :)


    You have moved into a dark place.
    It is pitch black. You are likely to be eaten by a grue.