πŸ“˜ Removing blanks from a string using Perl 6

Remove leading, trailing and double spaces from a given string.

This task often occurs when you need to clean the user input, such as from web forms, where leading or trailing spaces in, for example, names, are most likely user mistakes and should be removed.

Removing double and multiple spaces between words can be solved by using substitution:

my $string = 'Hello,     World!';
$string ~~ s:g/\s+/ /;

Don’t forget to make the substitution global with the :g adverb to find all the occurrences of repeated spaces.

Leading and trailing spaces can be removed with the trimroutine:

my $string = 'Hello, World! ';
say trim($string);

The trim routine exists as a self-standing function, as shown in the previous example, as well as a method of the Str class, so it can be called on a variable or on a string:

say $string.trim;
say ' Hello, World! '.trim;

There are also two routines, trim-leading and trim-trailing, which remove either only leading or only trailing spaces.

say 'Β‘' ~ '  Hi '.trim-leading;  # Β‘Hi␣␣
say '  Hi  '.trim-trailing ~ '!'; # β£β£Hi!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s