String::Compile::Tr - compile tr/// expressions
Version 0.06
use String::Compile::Tr;
my $search = '/+=';
my $replace = '-_';
my $s = 'De/0xv5y3w8BpLF8ubOo+w==';
trgen($search, $replace, 'd')->($s);
# $s = 'De-0xv5y3w8BpLF8ubOo_w'
The usual approach when operands of a tr///
operator shall be
variables is to apply eval
on a string to interpolate the operands.
The drawback of this approach are possible unwanted side effects induced
by the variables' content, e.g.
$search = '//,warn-trapped,$@=~tr/';
eval "tr/$search//d";
String::Compile::Tr
offers an alternative where the content of a
variable can be used as operand without eval
'ing it.
Instead the operands of a tr///
operator are overloaded at runtime
inside a constant eval '...'
.
trgen(*SEARCH*, *REPLACE*, *OPT*)
compiles an anonymous sub that
performs almost the same operation as tr/*SEARCH*/*REPLACE*/*OPT*
,
but allows variable operands.
trgen
is imported by default by use String::Compile::Tr
.
trgen(search, replace, [options])
trgen
returns an anonymous subroutine that performs an almost identical
operation as tr/search/replace/options
.
The tr
target may be given as an argument to the generated sub
or is the default input $_
otherwise.
trgen
will throw an exception if an invalid option is specified
or the tr
operation cannot be compiled.
Proposed usages of this module are:
use String::Compile::Tr;
my $search = 'abc';
my $replace = '123';
my $tr = trgen($search, $replace);
my $s = 'fedcba';
$tr->($s);
# $s is 'fed321' now
my @list = qw(axy bxy cxy);
$tr->() for @list;
# @list is now ('1xy', '2xy', '3xy');
print trgen($search, $replace, 'r')->('fedcba'); # 'fed321'
Character ranges are not supported in the search and replace lists.
All characters are interpreted literally.
This is caused by the fact that tr
does not support these neither.
It's the compiler that expands character ranges in tr
's operands
before handing them over.
Overloading constants in eval '...'
requires perl v5.10.
Jörg Sommrey, <git at sommrey.de>
This software is copyright (c) 2025 by Jörg Sommrey.
This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself.
"tr/*SEARCHLIST*/*REPLACEMENTLIST*/cdsr" in perlop
Exporter::Tiny::Manual::Importing
Regexp::Tr provides a similar functionality, though this eval
's
its oprands.