📘 Print squares using Perl 6

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

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