use warnings; use strict; sub make_translator { my ($from, $to, ) = @_; # this check may not be needed. # see tr/// docs for effect of unequal strings. die "from `$from' and to `$to' string lengths differ" if length($from) != length($to); return eval "sub { \$_[0] =~ tr{$from}{$to} }"; } my %trans = ( # translation mappings for target string offsets # at this # do this # offset, # translation. # 1 => make_translator ('abc' => 'XYZ'), 1 => sub { $_[0] =~ tr{abc} {XYZ} }, 3 => make_translator ('def' => 'PQR'), 99 => make_translator ('abc' => '987'), 0 => make_translator ('stu' => '*%&'), ); my %test = ( 'kaldm' => 'kXlPm', 'hbiej' => 'hYiQj', 'sytf' => '*ytR', ); # # works - both ST and for-loop variations # for my $word (keys %test) { # # my @chars = split '', $word; # # # map { $trans{$_}->($chars[$_]) } # 2. xlate char at offset. # # grep { $_ < @chars } # 1. that are in word... # # keys %trans; # 0. for all offsets... # # # for all offsets within the word... # for (grep { $_ < @chars } keys %trans) { # $trans{$_}->($chars[$_]); # translate char at offset. # } # # my $translated_word = join '', @chars; # # printf "%-5s -> %s \n", $word, $translated_word; # # print "ERROR: $word badly translated: \n" # . "should be: $test{$word} \n" # . " got: $translated_word \n" # if $translated_word ne $test{$word}; # # } # works - simplest, probably fastest while (my ($word, $translation) = each %test) { my $original = $word; # save copy: word translated in place printf "%-5s -> ", $word; # for all offsets within the word... for my $offset (grep { $_ < length $word } keys %trans) { # translate char in place: 3-arg substr() returns lvalue. # could translate groups of more than one character if # the width of the group could be defined for each # translation. $trans{$offset}->(substr $word, $offset, 1); } print qq($word \n); print "ERROR: $original badly translated: \n" . "should be: $translation \n" . " got: $word \n" if $word ne $translation; }
In reply to Re: tr at a given pos
by Anonymous Monk
in thread tr at a given pos
by FFRANK
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |