method trans

Documentation for method trans assembled from the following types:

class Cool

From Cool

(Cool) method trans

Defined as:

method trans(|)

Coerces the invocant to Str and calls Str.trans

class Str

From Str

(Str) method trans

multi method trans(Str:D: Pair:D \what*%n --> Str)
multi method trans(Str:D: *@changes:complement(:$c), :squash(:$s), :delete(:$d--> Str)

Replaces one or many characters with one or many characters. Ranges are supported, both for keys and values. Regexes work as keys. In case a list of keys and values is used, substrings can be replaced as well. When called with :complement anything but the matched value or range is replaced with a single value; with :delete the matched characters without corresponding replacement are removed. Combining :complement and :delete will remove anything but the matched values, unless replacement characters have been specified, in which case, :delete would be ignored. The adverb :squash will reduce repeated matched characters to a single character.

Example:

my $str = 'say $x<b> && $y<a>';
$str.=trans'<' => '«' );
$str.=trans'<' => '«''>' => '»' );
 
$str.=trans( [ '<'   , '>'   , '&' ] =>
             [ '&lt;''&gt;''&amp;' ]);
 
$str.=trans( ['a'..'y'=> ['A'..'z'] );
 
"abcdefghij".trans(/<[aeiou]> \w/ => '');                     # RESULT: «cdgh» 
 
"a123b123c".trans(['a'..'z'=> 'x':complement);            # RESULT: «axxxbxxxc» 
"a123b123c".trans('23' => '':delete);                       # RESULT: «a1b1c» 
"aaa1123bb123c".trans('a'..'z' => 'A'..'Z':squash);         # RESULT: «A1123B123C» 
"aaa1123bb123c".trans('a'..'z' => 'x':complement:squash); # RESULT: «aaaxbbxc» 

Please note that the behavior of the two versions of the multi method is slightly different. The first form will transpose only one character if the origin is also one character:

say "abcd".trans"a" => "zz" );  # OUTPUT: «zbcd␤» 
say "abcd".trans"ba" => "yz" ); # OUTPUT: «zycd␤» 

In the second case, behavior is as expected, since the origin is more than one char long. However, if the Pair in the multi method does not have a Str as an origin or target, it is handled to the second multi method, and behavior changes:

say "abcd".trans: ["a"=> ["zz"]; # OUTPUT: «zzbcd␤» 

In this case, neither origin nor target in the Pair are Str; the method with the Pair signature then calls the second, making this call above equivalent to "abcd".trans: ["a"] => ["zz"], (with the comma behind, making it a Positional, instead of a Pair), resulting in the behavior shown as output.