#!/usr/bin/perl -w use strict; use diagnostics; # Mappings between character sets my %M_2_UTF8 = ( 'A' => 'X', ); # default set my %Ma_2_UTF8 = ( 'A' => 'a', ); # set a my $CURRENTSET = \%M_2_UTF8; my @setqueue = (); # a stack where we push and pop # ESC-sequences my $switch_to_set_a = "\x1Ba"; my $reset = "\x1Bs"; # return to previous charset my %ESC = ( $switch_to_set_a => sub { push(@setqueue, $CURRENTSET); $CURRENTSET = \%Ma_2_UTF8; return ''; }, $reset => sub { $CURRENTSET = pop @setqueue; return ''; }, ); my $str = 'X|a|X'; my $esc_str = qq(A|${switch_to_set_a}A|${reset}A); my $convstr = fix($esc_str); if ($str eq $convstr) { print "ok\n"; } else { print "didn't work...\n"; } sub fix { my $s = shift; $s =~ s{(\x1B[abcs])|(.)} {repl($&)}ge; return $s; } sub repl { my $match = shift; if (exists $ESC{$match}) { return $ESC{$match}(); } elsif (exists $CURRENTSET->{$match}) { return $CURRENTSET->{$match}; } else { return $match; } } __END__