You can compress it in a string as you show, perhaps a little better with /r (with v5.14 +).
Or you can prepare a hash. It also frees the code from hard coding certain characters.
my %swap = (x => 'y', y => 'x', a => 'b', b => 'a');
// (defined-or) should handle the case when the last character is not in the hash, in which case $swap{$1} returns undef . Thanks to user52889 for the comment.
source share