Search code examples
perlprintingstdoutmoosetie

How can I modify the output of the PRINT function using Tie with a Moose implementation?


I can't exactly wrap my head around TIE just yet but the examples ( example-1 example-2 example-3 ) I've seen so far use a non-Moosy implementation, is there anyway to do this:

package MY_STDOUT;
use strict;
my $c = 0;
my $malformed_header = 0;
open(TRUE_STDOUT, '>', '/dev/stdout');
tie *STDOUT, __PACKAGE__, (*STDOUT);

sub TIEHANDLE {
    my $class = shift;
    my $handles = [@_];
    bless $handles, $class;
    return $handles;
}

sub PRINT {
    my $class = shift;
    if (!$c++ && @_[0] !~ /^content-type/) {
        my (undef, $file, $line) = caller;
        print STDERR "Missing content-type in $file at line $line!!\n";
        $malformed_header = 1;
    }
    return 0 if ($malformed_header);
    return print TRUE_STDOUT @_;
}
1;


use MY_STDOUT;
print "content-type: text/html\n\n"; #try commenting out this line
print "<html>\n";
print "</html>\n";

In a more Perl-Moosy way?

For example should I do

open(TRUE_STDOUT, '>', '/dev/stdout');
tie *STDOUT, __PACKAGE__, (*STDOUT);

in a BUILD{} function?

Would it make more sense to implement this as a Moosy class or as Moose::Role?

And finally, would I have to do something like

my $MY_STDOUT = MY_STDOUT->new();

to use it?


Solution

  • I've figured out how to do it with IO::Scalar

    https://gist.github.com/1250048

    Now I just need to figure out how to do it for STDOUT!