作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
您可以使用 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;
<a b c d e>
c
<a b c z e>
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;
<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
最佳答案
不知何故,AT-POS
方法没有被调用。 documentation提到了 ASSIGN-POS
的使用相反,所以我们开始:
class Bar
{
has @.grid is rw;
method AT-POS($y, $x) is rw { say "AT-POS $y, $x"; return-rw @!grid[$y;$x] }
method ASSIGN-POS($y, $x, $new) { say "ASSIGN-POS $y, $x"; @!grid[$y;$x] = $new }
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;
Cannot modify an immutable List ((k l m n o))
in method ASSIGN-POS at semilist-so.p6 line 8
in block <unit> at semilist-so.p6 line 16
Array
s,它们是可变的,你将能够做到这一点。
class Bar
{
has @.grid is rw;
method AT-POS($y, $x) is rw { return-rw @!grid[$y;$x] }
method ASSIGN-POS($y, $x, $new) { @!grid[$y;$x] = $new }
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;
关于raku - Perl 6 : writable multidimensional subscript access with AT-POS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53802528/
我是一名优秀的程序员,十分优秀!