2011-09-29 65 views
1

我不能确切地总结我的周围TIE头,只是还没有,但(example-1example-2example-3)我见过的例子至今使用非Moosy实现,反正有做到这一点:如何使用Tie实现Moose实现来修改PRINT函数的输出?

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"; 

在更多Perl-Moosy的方式?

比如我应该做的

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

在BUILD {}功能?

将它作为Moosy类或Moose :: Role来实现会更有意义吗?

最后,我不得不做一些像

my $MY_STDOUT = MY_STDOUT->new(); 

使用它?

回答

0

我已经想通了如何使用IO做::标

https://gist.github.com/1250048

现在我只需要弄清楚如何做到这一点的标准输出!

+0

要回答这个问题,您没有机会在别处回答,我绝不会让某人误解某些东西。 – ikegami