You can easily allow subscript access to your own classes using AT-POS:
class Foo
{
has @.grid;
method AT-POS($x) is rw { return-rw @!grid[$x] }
method Str { '<' ~ @!grid.join(' ') ~ '>' }
method gist { self.Str }
}
my $foo = Foo.new(:grid(<a b c d e>));
say $foo;
say $foo[2];
$foo[3] = 'z';
say $foo;
output:
<a b c d e>
c
<a b c z e>
But I need two-dimensional subscript access. I've figured out how to make this work for reading, but it dies when writing:
class Bar
{
has @.grid;
method AT-POS($y, $x) is rw { return-rw @!grid[$y;$x] }
method Str { '<' ~ @!grid».join(' ').join("\n ") ~ '>' }
method gist { self.Str }
}
my $bar = Bar.new(:grid(<a b c d e>, <f g h i j>, <k l m n o>));
say $bar;
say $bar[1;2];
$bar[2;3] = 'z';
say $bar;
output:
<a b c d e
f g h i j
k l m n o>
h
Too few positionals passed; expected 3 arguments but got 2
in method AT-POS at ./p6subscript line 25
in block <unit> at ./p6subscript line 33
Is there any way to make this work?