You could use something like Scope::Guard - lexically-scoped resource management to ensure it gets set back to :utf8
when you leave the scope, regardless of how (return, die, whatever):
#!/usr/bin/perl -w
use strict;
use Scope::Guard qw(guard);
binmode(STDOUT, ':utf8');
print(join(', ', PerlIO::get_layers(STDOUT)), "\n");
{
# When guard goes out of scope, this sub is guaranteed to be called:
my $guard = guard {
binmode(STDOUT, ':utf8');
};
binmode(STDOUT, ':raw');
print(join(', ', PerlIO::get_layers(STDOUT)), "\n");
}
print(join(', ', PerlIO::get_layers(STDOUT)), "\n");
Or, if you don't want to include a new dependency like Scope::Guard (Scope::Guard is awesome for this kind of localizing...):
#!/usr/bin/perl -w
use strict;
binmode(STDOUT, ':utf8');
print(join(', ', PerlIO::get_layers(STDOUT)), "\n");
{
my $guard = PoorMansGuard->new(sub {
binmode(STDOUT, ':utf8');
});
binmode(STDOUT, ':raw');
print(join(', ', PerlIO::get_layers(STDOUT)), "\n");
}
print(join(', ', PerlIO::get_layers(STDOUT)), "\n");
package PoorMansGuard;
sub new {
my ($class, $sub) = @_;
bless { sub => $sub }, $class;
}
sub DESTROY {
my ($self) = @_;
$self->{sub}->();
}