📘 Print squares using Perl 6

📘 Print squares using Raku

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

Print the squares of the numbers from 1 to 10.

To print the squares for a range of numbers, a loop is required. In Perl 6, if the body of the loop is simple, you can use the postfix notation:

say $_ ** 2 for 1..10;

The $_ variable is a loop variable, which receives the new value on each iteration.

Perl 6 offers the ** operator for calculating powers, so it can be used instead of the straightforward multiplication $_ * $_.

In the case of you needing a named loop variable, choose another form of a loop:

for 1..10 -> $x {
    say $x * $x;

Notice that there are no parentheses around the range in the forloop.

We also can create a list of squares using the mapfunction, as demonstrated in the following example:

.say for map {$_ ** 2}, 1..10;

Here, the range 1..10 is first converted to the list, each element of which is a square of the corresponding element of the initial list, and then it is printed one by one as before. The dot before say means calling the saymethod on the default variable, so both $_.say and .say are equivalent.

Leave a Reply

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