Substitutions

Regexes are also good for data manipulation. The subst method matches a regex against a string. With subst matches, it substitutes the matched portion of the string its the second operand:

    my $spacey = 'with    many  superfluous   spaces';

    say $spacey.subst(rx/ \s+ /, ' ', :g);
    # output: with many superfluous spaces

By default, subst performs a single match and stops. The :g modifier tells the substitution to work globally to replace every possible match.

Note the use of rx/ ... / rather than m/ ... / to construct the regex. The former constructs a regex object. The latter constructs the regex object and immediately matches it against the topic variable $_. Using m/ ... / in the call to subst creates a match object and passes it as the first argument, rather than the regex itself.