๐Ÿ“˜ Checking odd and even numbers in Perl 6

๐Ÿ“˜ Checking odd and even numbers in Raku

N. B. Perl 6 has been renamed to Raku. Click to read more.


Print the first ten odd numbers. Print the first ten even numbers.

Odd numbers are those that have a remainder after division by 2. This fact can be directly exploited in filtering the numbers and printing only those that match this definition.

.say if $_ % 2 for 1 .. 20;

To print even numbers, negate the condition by choosing another keyword:ย unless, instead ofย if:

.say unless $_ % 2 for 1 .. 20;

Numbers can be filtered using the grepbuilt-in function:

.say for grep {$_ % 2}, 1..20;

For the odd numbers, negate the condition by using the divisibility operator, which returnsย True when its first operand is divisible by the second with no remainder:

.say for grep {$_ %% 2}, 1..20;

Another interesting thing that Perl 6 offers is using a sequence. Show Perl the first elements of it, and it generates the rest:

my @odd = 1, 3 ... *;
say @odd[^10];

To print the even numbers, change the sample:

my @odd = 2, 4 ... *;
say @odd[^10];

Leave a Reply

Your email address will not be published. Required fields are marked *

Retype the CAPTCHA code from the image
Change the CAPTCHA codeSpeak the CAPTCHA code