#!/usr/bin/perl =pod SYNOPSIS use File::AnyEncoding; # unicode file writer - reader my $fun1 = new File::AnyEncoding('utf-16le'); my $text1 = "Hello world"; my $filepath1 = "AnyEncoding-test1.txt"; $fun1->write_file($filepath1, $text1); # writes file with specified encoding my $fun2 = new File::AnyEncoding(); my $text2 = $fun2->read_file($filepath1); # remembers the encoding found in $filepath1 $text2 =~s/world/unicode/; # modify file contents my $filepath2 = "AnyEncoding-test2.txt"; $fun2->write_file($filepath2, $text2); # writes file with encoding found in $filepath1 AUTHOR Rudif c/o Perlmonks =cut package File::AnyEncoding; use strict; use File::BOM qw( :all ); our %supported_encoding = map { $_ => 1 } ( 'NONE', 'UTF-8', 'UTF-16LE' ); sub new { my $class = shift; my $enc = shift // 'utf8'; my $self = {}; bless $self, $class; $self->set_encoding($enc); return $self; } sub set_encoding { my $self = shift; my $enc = shift; unless ( defined $enc && defined $supported_encoding{ $enc } ) { $enc = 'NONE'; #warn "defaulting to $enc"; } $self->{encoding} = $enc; } sub get_encoding { my $self = shift; $self->{encoding}; } sub write_file { my $self = shift; my $filepath = shift; my $text = join '', @_; my $enc = $self->{encoding}; my $FH; if ( $enc eq 'NONE' ) { open $FH, ">", $filepath; #open $FH, ">:raw:encoding(UTF-8):crlf:utf8", $filepath; } else { open $FH, ">:raw:encoding($enc):crlf:utf8", $filepath; print $FH "\x{FEFF}"; } print $FH $text; close $FH; } sub read_file { my $self = shift; my $filepath = shift; open my $FH, '<:bytes', "$filepath"; my ( $enc, $spillage ) = get_encoding_from_filehandle($FH); $enc = $self->set_encoding($enc); if ( $enc eq 'NONE' ) { #binmode $FH, ":encoding(UTF-8)"; close $FH; open $FH, '<', "$filepath"; } else { binmode $FH, ":encoding($enc)"; } my @lines = <$FH>; close $FH; wantarray ? @lines : join '', @lines; } 1;