#! /usr/local/bin/perl -w package MyEncode; use strict; BEGIN { unshift @INC, '.' }; require Exporter; use base qw (Exporter); # encode() and decode() are no longer needed because they are special cases # of recode(). our @EXPORT = qw (encode_open encode_close recode); use Encode; sub encode_open ($$;$) { my ($from, $to, $check) = @_; my $cd = { __check => ($check ||= 0) }; my $f = find_encoding ($from); unless (defined $f) { require Carp; Carp::croak ("Unknown encoding '$from'"); } $cd->{__from} = $f; my $t = find_encoding ($to); unless (defined $to) { require Carp; Carp::croak ("Unknown encoding '$to'"); } $cd->{__to} = $t; return $cd; } sub encode_close ($) { # Could call a method of the encodings that free allocated resources. undef $_[0]; } sub recode ($$) { return undef unless $_[0] && ref $_[0]; my $check = $_[0]->{__check}; my $uni = $_[0]->{__from}->encode ($_[1], $check); return undef if $check && length $_[1]; $_[1] = $_[0]->{__to}->decode ($uni, $check); return undef if (($check && length $uni) || !defined $_[1]); return length $_[1]; } 1; #__END__ use Benchmark; use Encode qw (from_to); use vars qw ($cd $lf); # FIXME: The opposite case (few iterations on a very large buffer) # shows from_to() in advance. Why? Actually the time spent in the # wrapper code should be negligible compared to the time spent in # the encoder. use constant COUNT => 1_000_000; use constant BYTES => 10; # This is mean enough to force Encode::from_to twice thru resolve_alias(). $cd = encode_open latin1 => 'latin2'; $lf = "\n" x BYTES; timethese COUNT, { from_to => "from_to \$lf, latin1 => 'latin2'", recode => 'recode $cd, $lf', }; encode_close $cd;