Search code examples
perlstdoutfilehandletiebinmode

Perl Cannot Binmode STDOUT After Untie Filehandle


I need to disable progressive buffering of an HTTP response.

I've got this working in Perl using a file handle class:

$|=1;
$TIE = tie(*STDOUT,__PACKAGE__);

Print statements are stored in an array and are retrieved via the following:

$buffer = tied *STDOUT;
$buffer = join('', @$buffer);
undef $TIE;
untie(*STDOUT);

If the HTTP response is text/html, it correctly displays in the browser.

However, for binary streams, I can't set binmode on STDOUT after it is untied, and the contents are corrupted.

If I save the HTTP response to a file, or if I do not use a file handle class, the binary data is preserved.

Any suggestions on how to force raw encoding? Thanks.


Solution

  • Something like this work?

    use strict;
    use warnings;
    use IO::Handle;
    
    my $io = IO::Handle->new;
    my $fh = $io->fdopen(fileno(STDOUT),"w");
    $fh->autoflush(1);
    
    my $TIE = tie( $fh ,__PACKAGE__);
    
    sub TIESCALAR { };
    
    binmode($fh);
    
    print $fh "Foo";