如何在Perl6中编写自定义访问器方法?
如果我有这个课程:
class Wizard {
has Int $.mana is rw;
}
Run Code Online (Sandbox Code Playgroud)
我可以做这个:
my Wizard $gandalf .= new;
$gandalf.mana = 150;
Run Code Online (Sandbox Code Playgroud)
假设我想在我的Perl6类中为一个setter添加一点检查而不放弃$gandalf.mana = 150;表示法(换句话说,我不想写这个:) $gandalf.setMana(150);.如果它试图设定负面法术力,该程序应该死亡.我该怎么做呢?Perl6文档提到它可以编写自定义访问器,但没有说明如何.
我正在尝试编写如下的紧凑行,代码是脚本的摘录,该脚本使用动态范围的特殊变量$*IN读取STDIN.你能告诉我如何正确写这条线吗?
这有效
for $*IN.lines() {
last when "" ;
say "VERBOSE \"$_ is the string\"";
$i=$i+1;
}
Run Code Online (Sandbox Code Playgroud)
.say "VERBOSE \"$_ is the string\"" for $*IN.lines() last when "";
Run Code Online (Sandbox Code Playgroud)
错误输出:
===SORRY!=== Error while compiling /usr/share/asterisk/agi-bin/agi-t1.p6
Two terms in a row
at /usr/share/asterisk/agi-bin/agi-t1.p6:5
------> .say? "Verbose \"$_\"" for $*IN.lines() last
expecting any of:
infix
infix stopper
statement end
statement modifier
statement modifier loop
Run Code Online (Sandbox Code Playgroud) 我想知道冒号与Perl 6中的方法和函数调用有什么关系.对于记录,我使用的是基于MoarVM版本2015.05构建的perl6版本2015.05-55-gd84bbbc.
我刚刚在Perl6规范测试中看到了以下内容(S32-io)(我添加了评论):
$fh.print: "0123456789A"; # prints '0123456789A' to the file
Run Code Online (Sandbox Code Playgroud)
据我所知,这相当于:
$fh.print("0123456789A"); # prints '0123456789A' to the file
Run Code Online (Sandbox Code Playgroud)
这两个似乎都采取了多个参数并平整列表:
$fh.print: "012", "345", "6789A"; # prints '0123456789A' to the file
$fh.print("012", "345", "6789A"); # prints '0123456789A' to the file
my @a = <012 345 6789A>;
$fh.print(@a); # prints '0123456789A' to the file
$fh.print: @a; # prints '0123456789A' to the file
Run Code Online (Sandbox Code Playgroud)
必须有一些理由拥有这两种不同的语法.有没有理由使用一种或另一种语法?
我还注意到,当用作方法时,我们必须使用:或()使用print:
$fh.print(@a); # Works
$fh.print: @a; # Works!
$fh.print @a; # …Run Code Online (Sandbox Code Playgroud) 我正在尝试对使用以下代码引发异常的功能进行测试:
use v6;
use Test;
plan *;
use lib "lib";
use Math::ConvergenceMethods;
sub f ($x) {return $x + 1;}
{
is-approx: bisection(&f, -2, 0), -1;
dies-ok: { bisection(&f, 3, 2) }, "Incorrect arguments";
}
done-testing;
Run Code Online (Sandbox Code Playgroud)
并且在我运行它时返回以下警告:
WARNINGS for /home/antonio/Code/perl6/Math-ConvergenceMethods/t/bisection.t:
Useless use of "-" in expression "-1" in sink context (line 13)
Useless use of constant string "Incorrect arguments" in sink context (lines 14, 14)
Run Code Online (Sandbox Code Playgroud)
我该如何解决?