🎥 The Pearls of Raku, Issue 2

The Pearls of Raku for your pleasure! The “with” statement, and setting a topic when working with regexes. Also a video with a full review of the Raku solutions 069-2.

Let me present a few more interesting findings that I discovered by looking at the Raku solutions to the Task 2 of Week 69 of Perl Weekly Challenge.

The Pearls of Raku for your pleasure!

with

In Raku, there is a with statement, which is a kind of a combination of if and given.

The similarity with if is that it is a conditional check, but it checks if the value is defined (not if it is True).

The similarity with given is that it also sets the topic.

You can see the behaviour in the following short example:

my $s;
say 'Not defined' with $s; # Not printed

# $s = '';
# $s = 0;
$s = 'abc';
say 'Defined' with $s; # Defined
.say with $s;          # abc

The first phrase is not printed as the variable $s is not defined there. After you give a value (even if it is an empty string or zero), the with statement passes the control to its block.

In the last line, you can see the call of .say with a dot in front of it. This is possible because with sets the topic to $s.

The above examples were using the postfix form of with, but you can use it in a direct order:

with $s {.say} # abc

Also examine orwith and without.

Get the value using a regex

How to you get an integer from the following string?

my $s = 'S5';

My approach was a two-line solution that I really did not like:

$s ~~ m/(\d+)/;
my $limit = +$/[0];

In one of the challenge solutions, I saw the following approach:

my $limit = .Int for $s ~~ m/(\d+)/;
say $limit;

Here, for is looping over the only value found in the string. For each of them (that is, for the only one), the Int method is called. So, we get the value in a single line.

We can use given here, or even with:

$limit = .Int given $s ~~ m/(\d+)/;

$limit = .Int with $s ~~ m/(\d+)/;

Raku challenge 069-2 review

→ Navigation to the Raku challenges post series

2 thoughts on “🎥 The Pearls of Raku, Issue 2”

  1. It’s always fun to see different approaches/styles. Of course, since TMTOWTDI, I have another alternative to suggest. You had:

    > my $limit = .Int with $s ~~ m/(\d+)/;

    My preferred version would be

    > my $limit = +($s ~~ /\d+/);

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