Reader small image

You're reading from  Perl 6 Deep Dive

Product typeBook
Published inSep 2017
Reading LevelIntermediate
PublisherPackt
ISBN-139781787282049
Edition1st Edition
Languages
Right arrow
Author (1)
Andrew Shitov
Andrew Shitov
author image
Andrew Shitov

Andrew Shitov has been a Perl enthusiast since the end of the 1990s, and is the organizer of over 30 Perl conferences in eight countries. He worked as a developer and CTO in leading web-development companies, such as Art. Lebedev Studio, Booking dotCom, and eBay, and he learned from the "Fathers of the Russian Internet", Artemy Lebedev and Anton Nossik. Andrew has been following the Perl 6 development since its beginning in 2000. He ran a blog dedicated to the language, published a series of articles in the Pragmatic Perl magazine, and gives talks about Perl 6 at various Perl events. In 2017, he published the Perl 6 at a Glance book by DeepText, which was the first book on Perl 6 published after the first stable release of the language specification.
Read more about Andrew Shitov

Right arrow

Control Flow

In this chapter, we will be talking about the main elements in controlling the flow of programs in Perl 6. Most programs are not just a list of instructions, but they should rather react to user input, take decisions based on calculated data, and so on.

In this chapter, we will cover the following topics:

  • Code blocks and the do keyword
  • Conditional checks
  • Loops
  • Breaking the loop body
  • Collecting data using gather and take
  • Setting the topic
  • Executing code only once

Understanding code blocks and variable scoping

In the previous chapter, we discussed variables, which are named entities that you use in a program. As in many programming languages, in Perl 6, the names are visible inside their scope and not outside of it.

Take, for instance, a simple program, where the $name variable is only used once, as follows:

my $name = 'Mark';
say "Hello, $name!";

The variable can be reused after it is used in printing the greeting:

my $name = 'Mark';
say "Hello, $name!";

$name = 'Carl';
say "Hello, $name!";

This works because both the printing statements are located in the same scope and the $name variable is visible there.

A block in Perl 6 is a piece of code that is located inside a pair of curly braces. A block creates its own scope. Thus, a variable declared in a block is only visible inside...

Conditional checks

Taking decisions based on conditions is one of the fundamental needs in programming. The if keyword changes the flow of the program, depending on the result of a Boolean test. Considering the following code:

my $x = 5;
if $x < 10 {
say "$x < 10"; # 5 < 10
}

In this example, you can see the syntax used with the if keyword. The keyword is followed by a Boolean condition $x < 10, followed by the block of code in the curly braces. Unlike Perl 5, parentheses around the condition are not necessary.

The block of code is only executed if the condition evaluates to True.

The if statement can be accomplished by the else branch, which will take control when the condition is False:

my $x = 11;
if $x < 10 {
say "$x < 10";
}
else {
say "$x >= 10"; # 11 >= 10
}

With the given value of $x, the program executes the code...

Using loops

Loop constructions help organize repeated actions. There are a few different options in Perl 6 for creating a loop. Let's start with the one that is similar to traditional loops in C style.

The loop cycle

The loop keyword expects three elements to control the number or repetitions of the loop body. Consider the following code snippet:

loop (my $c = 0; $c < 5; $c++) {
say $c;
}

In this example, $c is the counter of the loop iterations. This variable is declared and initialized immediately after the loop keyword—my $c = 0. The body of the loop is executed if the condition $c < 5 is True. After the iteration, the $c++ statement is executed, which increments the counter, and the cycle repeats....

Executing code once

In Perl 6, interestingly, it is possible to execute part of the body only once. For example, in the next loop, there should be four iterations done, but the first message will be printed only once:

for 1, 2, 3, 4 {
once {
say 'Looping from 1 to 4';
}
say "Current value is $_";
}

The preceding code prints the following output:

Looping from 1 to 4
Current value is 1
Current value is 2
Current value is 3
Current value is 4

The block of code after the once keyword was executed only once.

This also works with loops of other types, for example, with the loop cycle. Considering the following code snippet:

loop (my $c = 1; $c != 5; $c++) {
once say 'Looping from 1 to 4';
say "Current value is $c";
}

Notice that no curly braces are needed if you only have a single instruction to be executed once.

The once keyword...

Collecting data with gather and take

Preparing data lists can be very expressively organized with a pair of keywords in Perl 6—gather and take. The easiest way to understand how that works is by taking a look at the following example:

my @data = gather {
take 'a';
take 'b';
}

say @data;

The block of code after the gather keyword returns a sequence that is saved in the @data array. The elements of the sequence are provided by the take keywords. So, there will be two elements in @data, as you can see here:

[a b]

Let's consider a bigger example. It contains a two-dimensional matrix of integer numbers and a list of instructions. The instructions are the four directions—left, right, up, and down, and a command— take-it. You should start at the center of the matrix, then move the current position according to the instructions, and pick...

Setting the topic with given

In the example in the previous section, we used a chained ifelsif construction. Let's take a look at this once again:

if    $step eq 'up'      {$y--}
elsif $step eq 'down' {$y++}
elsif $step eq 'right' {$x++}
elsif $step eq 'left' {$x--}
elsif $step eq 'take-it' {take @matrix[$y][$x]}

It is clearly seen that all the branches contain the same code, which compares the current value of the $step variable with one of the predefined values. While being simple and straightforward, this is not the most elegant way of doing such comparisons.

In some languages such as C and C++, the switch and case keywords help reorganize the if-else chain. In Perl 6, we use given and when. The preceding code can be rewritten in the following way:

given $step {
when 'up' {$y--}
when ...

Summary

In this chapter, we covered control flow, which Perl 6 offers for traditional procedural programming. We talked about executing code blocks and taking decisions using the keywords if, else, and elsif. We also talked about different loops—the basic loop, for loops, and the repeat, until, and while loops with pre-conditions or post-conditions. Then we looked at using the gathertake pair to collect data and the way Perl 6 works with topics with the help of the given and when keywords.

Perl 6 is not just capable of working with the procedural programming style. You will find more information about other paradigms in Chapter 13, Concurrent Programming, Chapter 14, Functional Programming, and Chapter 15, Reactive Programming.

Meanwhile, in the next chapter, we will discuss another level for organizing code and subroutines.

...
lock icon
The rest of the chapter is locked
You have been reading a chapter from
Perl 6 Deep Dive
Published in: Sep 2017Publisher: PacktISBN-13: 9781787282049
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €14.99/month. Cancel anytime

Author (1)

author image
Andrew Shitov

Andrew Shitov has been a Perl enthusiast since the end of the 1990s, and is the organizer of over 30 Perl conferences in eight countries. He worked as a developer and CTO in leading web-development companies, such as Art. Lebedev Studio, Booking dotCom, and eBay, and he learned from the "Fathers of the Russian Internet", Artemy Lebedev and Anton Nossik. Andrew has been following the Perl 6 development since its beginning in 2000. He ran a blog dedicated to the language, published a series of articles in the Pragmatic Perl magazine, and gives talks about Perl 6 at various Perl events. In 2017, he published the Perl 6 at a Glance book by DeepText, which was the first book on Perl 6 published after the first stable release of the language specification.
Read more about Andrew Shitov