๐Ÿ“˜ Increasing digits by one using Perl 6

In the given integer number, replace all the digits so that 1 becomes 2, 2 becomes 3, etc., and 9 becomes 0.

This task can be approached both mathematically and string-wise. In Perl 6, regexes seem to be the best match. Although a number is an example of the numeric data type, Perl 6 allows seamless changes when you want to start working with them as with strings.

In the proposed solution, a number is matched against a regex.

my $number = 564378901;
$number ~~ s:g/ (\d) /{ ($0 + 1) % 10 }/;
say $number;

Similar to the code of Task 76,ย Double each character, a global replacement happens. The target is a digit,ย \d. (We ignore the fact that theย \d character class matches 580 different characters in the Unicode space, see Task 39,ย Unicode digits.)

So, a digit (treated as a character) lands in theย $0 variable. In the replacement part ofย s///, a block of code is placed. It takes the value ofย $0 and addsย 1 to it. As theย + operator expects numeric operands, the character is converted to an integer and is incremented after it. The modulo operator keeps the value in the range between 0 and 9 (including), The new value is converted back to a string character, which replaces the original digit that was captured.

In the given example,ย 675489012 is printed.Notice that it was not possible to use an increment operator in the replacement. An attempt to make itย $0++ would lead to an exception as theย ++ operator needs a mutable object.

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