How to pass pointer to a container from function?

Viewed 204

I can bind containers to new names:

my %h;
my $p := %h{ "a" }{ "b" }{ "c" };
$p = 1;
say %h;

Which outputs expected:

{a => {b => {c => 1}}}

But what if I need to return such pointer from subroutine?

my %h;
sub get-pointer {
    my $p := %h{ "a" }{ "b" }{ "c" };
    return $p;
};
my $q := get-pointer();
$q = 1;
say %h;

Gives:

Cannot assign to a readonly variable or a value

That thing puzzles me - $p.WHERE and $q.WHERE give the same address, so why is it suddenly read-only?

1 Answers

Nevermind, I had some tunnel-vision moment and wanted aliases to behave as C pointers.

Found it clearly explained here at Raku Documentation.

The sub return will return values, not containers. Those are immutable

To return a mutable container, use return-rw.

Related