Encode::Mapper - Perl extension for intuitive, yet efficient construction of mappings for Encode |
Encode::Mapper - Perl extension for intuitive, yet efficient construction of mappings for Encode
$Revision: 1.18 $ $Date: 2004/02/08 14:08:24 $
use Encode::Mapper; ############################################# Enjoy the ride ^^
use Encode::Mapper ':others', ':silent'; # syntactic sugar for compiler options ..
Encode::Mapper->options ( # .. equivalent, see more in the text 'others' => sub { shift }, 'silent' => 1, );
Encode::Mapper->options ( # .. resetting, but not to use 'use' !!! 'others' => undef, 'silent' => 0 );
## Types of rules for mapping the data and controlling the engine's configuration #####
@rules = ( 'x', 'y', # single 'x' be 'y', unless greediness prefers .. 'xx', 'Y', # .. double 'x' be 'Y' or other rules
'uc(x)x', sub { 'sorry ;)' }, # if 'x' follows 'uc(x)', be sorry, else ..
'uc(x)', [ '', 'X' ], # .. alias this *engine-initial* string 'xuc(x)', [ '', 'xX' ], # likewise, alias for the 'x' prefix
'Xxx', [ sub { $i++; '' }, 'X' ], # count the still married 'x' );
## Constructors of the engine, i.e. one Encode::Mapper instance #######################
$mapper = Encode::Mapper->compile( @rules ); # engine constructor $mapper = Encode::Mapper->new( @rules ); # equivalent alias
## Elementary performance of the engine ###############################################
@source = ( 'x', 'xx', 'xxuc(x)', 'xxx', '', 'xx' ); # distribution of the data .. $source = join '', @source; # .. is ignored in this sense
@result = ($mapper->process(@source), $mapper->recover()); # the mapping procedure @result = ($mapper->process($source), $mapper->recover()); # completely equivalent
$result = join '', map { ref $_ eq 'CODE' ? $_->() : $_ } @result;
# maps 'xxxxxuc(x)xxxxx' into ( 'Y', 'Y', '', 'y', CODE(...), CODE(...), 'y' ), .. # .. then converts it into 'YYyy', setting $i == 2
@follow = $mapper->compute(@source); # follow the engine's computation over @source $dumper = $mapper->dumper(); # returns the engine as a Data::Dumper object
## Module's higher API implemented for convenience ####################################
$encoder = [ $mapper, Encode::Mapper->compile( ... ), ... ]; # reference to mappers $result = Encode::Mapper->encode($source, $encoder, 'utf8'); # encode down to 'utf8'
$decoder = [ $mapper, Encode::Mapper->compile( ... ), ... ]; # reference to mappers $result = Encode::Mapper->decode($source, $decoder, 'utf8'); # decode up from 'utf8'
Encode::Mapper serves for intuitive, yet efficient construction of mappings for Encode. The module finds direct application in Encode::Arabic and Encode::Korean, providing an object-oriented programming interface to convert data consistently, follow the engine's computation, dump the engine using Data::Dumper etc.
It looks like the author of the extension ... ;) preferred giving formal and terse examples to writing English. Please, see Encode::Arabic and Encode::Korean, where Encode::Mapper is used for solving complex real-world problems.
The module's core is an algoritm which, from the rules given by the user, builds a finite-state transducer, i.e. an engine performing greedy search in the input stream and producing output data and side effects relevant to the results of the search. Transducers may be linked one with another, thus forming multi-level devices suitable for nontrivial encoding/decoding tasks.
The rules declare which input sequences of bytes to search for, and what to do upon their occurence. If the left-hand side (LHS) of a rule is the longest left-most string out of those applicable on the input, the righ-hand side (RHS) of the rule is evaluated. The RHS defines the corresponding output string, and possibly controls the engine as if the extra text were prepended before the rest of the input:
$A => $X # $A .. literal string # $X .. literal string or subroutine reference $A => [$X, $Y] # $Y .. literal string for which 'length $Y < length $A'
The order of the rules does not matter, except when several rules with the same LHS are stated. In such a case, redefinition warning is usually issued before overriding the RHS.
$opts
.
If $opts
is recognized, it is used to modify the compiler options
locally for the engine being
constructed. If an option is not overridden, its global setting holds.
The compilation algorithm, and the search algorithm itself, were inspired by Aho-Corasick and Boyer-Moore algorithms, and by the studies of finite automata with the restart operation. The engine is implemented in the classical sense, using hashes for the transition function for instance. We expect to improve this to Perl code evaluation, if the speed-up is significant.
It is to explore the way Perl's regular expressions would cope with the task, i.e. verify our initial doubts which prevented us from trying. Since Encode::Mapper's functionality is much richer than pure search, simulating it completely might be resource-expensive and non-elegant. Therefore, experiment reports are welcome.
compile
constructor.
split
into bytes, and there is just no need for the user to join
his/hers strings or lines of data. Note the unveiled properties of the Encode::Mapper
class as well:
sub process ($@) { # returns the list of search results performed by Mapper my $obj = shift @_; my (@returns, $phrase, $token, $q);
use bytes; # ensures splitting into one-byte tokens
$q = $obj->{'current'};
foreach $phrase (@_) { foreach $token (split //, $phrase) { until (defined $obj->{'tree'}[$q]->{$token}) { push @returns, @{$obj->{'bell'}[$q]}; $q = $obj->{'skip'}[$q]; } $q = $obj->{'tree'}[$q]->{$token}; } }
$obj->{'current'} = $q;
return @returns; }
recover
is called on the object without the other two
optional parameters setting the initial and the final state, respectively.
sub recover ($;$$) { # returns the 'in-progress' search result and resets Mapper my ($obj, $r, $q) = @_; my (@returns);
$q = $obj->{'current'} unless defined $q;
until ($q == 0) { push @returns, @{$obj->{'bell'}[$q]}; $q = $obj->{'skip'}[$q]; }
$obj->{'current'} = defined $r ? $r : 0;
return @returns; }
local $\ = "\n"; local $, = ":\t"; # just define the display
foreach $result ($mapper->compute($source)) { # follow the computation
print "Token" , $result->[0]; print "Source" , $result->[1]; print "Output" , join " + ", @{$result->[2]}; print "Target" , $result->[3]; print "Bell" , join ", ", @{$result->[4]}; print "Skip" , $result->[5]; }
sub dumper ($;$) { my ($obj, $ref) = @_;
$ref = ['L', 'H', 'mapper'] unless defined $ref;
require Data::Dumper;
return Data::Dumper->new([$obj->{'null'}{'list'}, $obj->{'null'}{'hash'}, $obj], $ref); }
$ref
is defined, the information is also print
ed into the $ref
erenced stream, or to
STDERR
if $ref
is not a filehandle.
In the Encode world, one can work with different encodings and is also provided a function for telling if the data are in Perl's internal utf8 format or not. In the Encode::Mapper business, one is encouraged to compile different mappers and stack them on top of each other, getting an easy-to-work-with filtering device.
In combination, this module offers the following encode
and decode
methods. In their prototypes,
$encoder
/$decoder
represent merely a reference to an array of mappers, although mathematics might
do more than that in future implementations ;)
Currently, the mappers involved are not reset with recover
before the computation. See the --join
option for more comments on the code:
foreach $mapper (@{$_[2]}) { # either $encoder or $decoder $join = defined $mapper->{'join'} ? $mapper->{'join'} : defined $option{'join'} ? $option{'join'} : ""; $text = join $join, map { UNIVERSAL::isa($_, 'CODE') ? $_->() : $_ } $mapper->process($text), $mapper->recover(); }
$enc
is defined, the $text
is encoded into that encoding, using Encode. Then, the
$encoder
's engines are applied in series on the data. The returned text should have the utf8
flag off.
$text
is run through the sequence of engines in $decoder
. If the result does not have the
utf8 flag on, decoding from $enc
is further performed by Encode. If $enc
is not defined,
utf8 is assumed.
The language the Encode::Mapper engine works on is not given exclusively by the rules
passed as parameters to the compile
or new
constructor methods. The nature of the compilation is
influenced by the current setting of the following options:
'override' => [ # override rules of these LHS .. there's no other tricks ^^
( # combinations of '<' and '>' with the other bytes map {
my $x = chr $_;
"<" . $x, [ "<" . $x, ">" ], # propagate the '>' sign implying .. ">" . $x, [ $x, ">" ], # .. preservation of the bytes
} 0x00..0x3B, 0x3D, 0x3F..0xFF ),
">>", ">", # stop the whole process .. "<>", "<>", # .. do not even start it
"><", [ "<", ">" ], # rather than nested '<' and '>', .. "<<", [ "<<", ">" ],
">\\<", [ "<", ">" ], # .. prefer these escape sequences ">\\\\", [ "\\", ">" ], ">\\>", [ ">", ">" ],
">", ">", # singular symbols may migrate right .. "<", "<", # .. or preserve the rest of the data ]
To preserve the 'other' bytes, you can use
'others' => sub { shift } # preserve every non-treated byte
the effect of which is similar to including the map
to the --complement
rules:
'complement' => [ ( map { ( chr $_ ) x 2 } 0x00..0xFF ), ... ] # ... is your rules
You may of course wish to return undefined values if there are any non-treated bytes in the input. In
order for the undef
to be a correct RHS, you have to protect it once more by the sub
like this:
'others' => sub { sub { undef } }
encode
and decode
, too. If not, either the current value of the option
or the empty string will help instead.
The keywords of options can be in mixed case and/or start with any number of dashes, and the next element in the list is taken as the option's value. There are special keywords, however, beginning with a colon and not gulping down the next element:
'others' => sub { shift }
explained above.
'silent' => 1
, or rather to the maximum silence if more degrees of it are introduced
in the future.
'join' => ''
. Use this option if you are going to dump and load the new engine often,
and if you do not miss the list-supporting uniformity of process
and recover
.
Compiler options are associated with package names in the %Encode::Mapper::options
variable, and confined
to them. While options
and import
perform the setting with respect to the caller package, accessing
the hash directly is neither recommended, nor restricted.
There is a nice compile-time invocation of import
with the use
Encode::Mapper LIST
idiom, which you
might prefer to explicit method calls. Local modification of the package's global setting that applies just
to the engine being constructed is done by supplying the options as an extra parameter to compile
.
use Data::Dump 'dump'; # pretty data printing is below
$Encode::Mapper::options{'ByForce'} = { qw ':others - silent errors' };
package ByMethod; # import called at compile time # no warnings, 'silent' is true Encode::Mapper->options('complement' => [ 'X', 'Y' ], 'others' => 'X'); use Encode::Mapper 'silent' => 299_792_458;
package main; # import called at compile time # 'non-existent' may exist once print dump %Encode::Mapper::options; use Encode::Mapper ':others', ':silent', 'non-existent', 'one';
# ( # "ByMethod", # { complement => ["X", "Y"], others => "X", silent => 299_792_458 }, # "ByForce", # { ":others" => "-", silent => "errors" }, # "main", # { "non-existent" => "one", others => sub { "???" }, silent => 1 }, # )
$class
is defined, enforces the options in the list globally for the calling package. The return value
of this method is the state of the options before the proposed changes were set. If $class
is undefined,
nothing is set, only the canonized forms of the declared keywords and their values are returned.
options
, provided there are some
elements in the list.
There are related theoretical studies which the implementation may have touched. You might be interested in Aho-Corasick and Boyer-Moore algorithms as well as in finite automata with the restart operation.
Encode, Encode::Arabic, Encode::Korean, Data::Dumper
Otakar Smrz, http://ufal.mff.cuni.cz/~smrz/
eval { 'E<lt>' . 'smrz' . "\x40" . ( join '.', qw 'ufal mff cuni cz' ) . 'E<gt>' }
Perl is also designed to make the easy jobs not that easy ;)
Copyright 2003, 2004 by Otakar Smrz
This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
Encode::Mapper - Perl extension for intuitive, yet efficient construction of mappings for Encode |