Some tips for working with hashes in Raku

In this blog post, I am giving a number of examples of how you can use hashes in the Raku programming language in a correct and incorrect ways and explain how to avoid the chance to mislead yourself.

The fact that Raku has no explicit references combined with the possibility to omit parentheses can sometimes mislead a developer. In this blog post, I will give a few examples of where I had some issues with trying to make it work.

First, here is a data structure that we’ll play with:

my %capitals =
    France => 'Paris',
    Italy => 'Rome';

(I hope you will be able to visit the mentioned countries and the great cities pretty soon.)

The %capitals variable is a hash that contains two key—value pairs. You can dump it to the console with a built-in Rakudo’s routine dd:

dd %capitals; 
# You will see this output:
# Hash %capitals = {:France("Paris"), :Italy("Rome")}


If you are used to work with Perl, make sure you are not using curly braces when accessing the element.

This is correct:

say %capitals<France>; # Paris
say %capitals<Italy>;  # Rome

This is wrong:

say %capitals{France};
say %capitals{Italy};

Raku expects that you have some executable code inside curly braces, so if you do not define the functions named France and Italy, you’ll get a compile error:

===SORRY!=== Error while compiling /Users/ash/raku-test/return-hash.raku
 Undeclared names:
     France used at line 11
     Italy used at line 12

So, with this kind of brackets, you need either a variable or a string to make it work as expected:

my $country = 'France';
say %capitals{$country}; # Paris
say %capitals{'Italy'};  # Rome


There is a chance to mislead yourself if you try to think of a hash name as of a reference and make it a scalar:

my $capitals =
    France => 'Paris',
    Italy => 'Rome';

This code compiles with a warning:

Useless use of "Italy => 'Rome'" in sink context

For Raku, this code means you are trying to create two independent pairs and assign them to some scalar variables, but there is only one such variable. Dump it to see what it contains:

dd $capitals; # Pair $capitals = :France("Paris")

This time, this is not a hash, but a single pair, and the second country—capital pair is lost (that’s what the warning meant).

It is possible to avoid the warning by supplying the compiler with another scalar container:

my ($capital1, $capital2) =
    France => 'Paris',
    Italy => 'Rome';

Probably, this is not what you wanted in the beginning. You created a couple of pairs, each keeping a single city:

dd $capital1; # Pair $capital1 = :France("Paris")
dd $capital2; # Pair $capital2 = :Italy("Rome")

say $capital1<France>; # Paris
say $capital2<Italy>;  # Rome;

If you try to cross-access the keys, you get Nils, as each pair contains exactly one key and exactly one value:

say $capital1<Italy>;  # Nil
say $capital2<France>; # Nil


OK, now let us use curly braces in our attempts to create a hash. First, store it in the variable that comes with the % sigil:

my %capitals = {
    France => 'Paris',
    Italy => 'Rome'

Then, with $:

my $capitals = {
    France => 'Paris',
    Italy => 'Rome'

The fun fact is that you can notice only a tiny difference if you dump the variables:

dd %capitals;
# Hash %capitals = {:France("Paris"), :Italy("Rome")}

dd $capitals;
# Hash $capitals = ${:France("Paris"), :Italy("Rome")}

When accessing the elements, there is no difference:

say %capitals<France>; # Paris
say %capitals<Italy>;  # Rome;

say $capitals<France>; # Paris
say $capitals<Italy>;  # Rome;

In Raku, a scalar variable such as $capitals is just a container that can still keep a hash object.

A $-prefixed variable contains a single object, and you can easily see it if you iterate over it. Compare:

.WHAT.say for %capitals;
# (Pair)
# (Pair)

.WHAT.say for $capitals;
# (Hash)


If you are not confused so far, then you are prepared to the next example. Define the following two functions that intend to return the same hash data with the country—capital pairs:

sub get_capitals() {
        France => 'Paris',
        Italy => 'Rome';

sub get_capitals1() {
    return {
        France => 'Paris',
        Italy => 'Rome',

Notice the differences in how a return object is created. The difference gets less visible when you start using the functions, especially if they are defined in a separate module, for example. Let’s save the results of these two functions in different variables, a scalar and a hash. Limit ourselves to the first function first:

my %data = get_capitals();
my $data = get_capitals();

When you save it to a hash, you get what you want:

dd %data;
# Hash %data = {:France("Paris"), :Italy("Rome")}
say %data<France>; # Paris
say %data<Italy>;  # Rome

With the scalar variable on the left side of the assignment, things are less straightforward. Unlike the example in section 2, the second pair is not ignored, and you return a list.

dd $data;
# List $data = $(:France("Paris"), :Italy("Rome"))
dd $data[0]; # :France("Paris")

say $data[0]<France>; # Paris
say $data[1]<Italy>; # Rome

# say $data<France>;
# Error: Type List does not support associative indexing.

As you can see, you get a list of pairs, and you need to explicitly subscript it to get the values. This may be a very unexpected surprise in practice.

With the second function, the one that use curly braces to build a hash before returning it, chances to make it wrong vanish:

%data = get_capitals1();
dd %data;
# Hash %data = {:France("Paris"), :Italy("Rome")}
say %data<France>; # Paris
say %data<Italy>;  # Rome

$data = get_capitals1();
dd $data; 
# Hash $data = ${:France("Paris"), :Italy("Rome")}
say $data<France>; # Paris
say $data<Italy>;  # Rome

And that’s all for now. You can find all the examples in the return-hash.raku file in my GitHub repository.

Leave a Reply

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