Encode::Mapper(3pm) | User Contributed Perl Documentation | Encode::Mapper(3pm) |
Encode::Mapper - Rewrite rules compiler and interpreter
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. It provides 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 where Encode::Mapper is used for solving complex real-world problems.
The module's core is an algorithm 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 occurrence. 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.
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.
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; }
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); }
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(); }
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 } }
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:
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 }, # )
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, Data::Dumper
Encode Arabic: Exercise in Functional Parsing
<http://ufal.mff.cuni.cz/padt/online/2006/06/encode-arabic.html>
Otakar Smrz "<otakar-smrz users.sf.net>", <http://otakar-smrz.users.sf.net/>
Copyright (C) 2003-2014 Otakar Smrz
This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
2022-10-16 | perl v5.34.0 |