perl-unicode

Re: Determining IO layer set on filehandle

2010-01-29 11:33:53

Am 29.01.2010 um 17:28 schrieb Nicholas Clark:

On Fri, Jan 29, 2010 at 02:22:06PM +0100, Michael Ludwig wrote:
Filehandles may have IO layers applied to them, like :utf8 or :raw.
One of the ways to achieve that is to use the binmode() function.

 binmode $fh, ':utf8';

What I want to achieve is to set the STDOUT filehandle to ':raw' and
then to restore the previous IO layers.

Is there a way to determine the IO layers applying to a filehandle
just from the filehandle itself?

I think you want PerlIO::get_layers($fh)

I'm not sure where it's documented.

Thanks, just what I was looking for! It's documented in PerlIO(3pm).

It appears you can use that information to restore a filehandle
configuration:

# Gut: STDOUT duplizieren und Duplikat umstellen.
# STDOUT (global) wird nicht verstellt.
sub out_bin_good {
    open my $fh, '>&STDOUT' or die "dup STDOUT: $!";
    binmode $fh, ':raw' or die "binmode: $!";
    print $fh "BINÄR 3\t", @_;
    print STDERR "* layer: $_\n" for PerlIO::get_layers( $fh );
}

# Auch gut: IO-Modus sichern und wiederherstellen.                              
                                                                                
sub out_bin_also_good {
    my @layers = PerlIO::get_layers( STDOUT );
    binmode STDOUT, ':raw' or die "binmode: $!";
    print "BINÄR 4\t", @_;
    print STDERR "* layer: $_\n" for PerlIO::get_layers( STDOUT );
    my $layers = join '', map ":$_", @layers;
    binmode STDOUT, $layers;
    print STDERR "reset STDOUT to $layers\n";
    print STDERR "* layer: $_\n" for PerlIO::get_layers( STDOUT );
}

-- 
Michael.Ludwig (#) XING.com