perl6/rakudo:如何更改变量的数据类型?
#!perl6
use v6;
my $m = 70;
my $n = 30;
( $m div $n ).say;
第一个示例有效,但第二个示例无效。我想这是因为在第二个示例中变量值是字符串。如果我的猜测是正确的,我如何将字符串变量更改为整数变量?
#!perl6
use v6;
my $m = '70';
my $n = '30';
( $m div $n ).say;
# No applicable candidates found to dispatch to for 'infix:<div>'.
# Available candidates are:
# :(Int $a, Int $b)
# in main program body at line 7:./perl5.pl
#!perl6
use v6;
my $m = 70;
my $n = 30;
( $m div $n ).say;
The first examples works, but the second doesn't. I suppose it's because in the second example the variable-values are strings. If my guess is right, how could I change the string-variables to integer-variables?
#!perl6
use v6;
my $m = '70';
my $n = '30';
( $m div $n ).say;
# No applicable candidates found to dispatch to for 'infix:<div>'.
# Available candidates are:
# :(Int $a, Int $b)
# in main program body at line 7:./perl5.pl
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你总是可以手动转换为 Int
实际上我希望前缀:<+>会像中那样工作,
但它只是“Num”,并且 sig 需要“Int”,我不确定是否应该这样。
更新:
+$m
现在可以工作了。You can always manually cast to Int
Actually I would have hoped that prefix:<+> would work as in
But it just "Num"ifies and the sig requires "Int", I am not sure if it should be this way or not.
UPDATE:
+$m
now works.我有点认为第二种形式也应该有效(首先强制转换为 Int,然后进行整数除法)。我将从其他 Perl 6 开发人员那里得到一些反馈,如果他们同意,我会修复它。 (更新:事实证明 infix: 显然不是强制的,而是指定返回与参数相同类型的值。这通常不适用于 Str)。
正如 Pat 指出的那样,
+$m
也应该有效,这是 Rakudo 中长期存在的限制。一般来说,类型的强制转换是通过
$variable.Typename
完成的,我相信这适用于当今 Rakudo 中的所有数字类型。I kinda think that the second form should work too (coerce to Int first, and then do integer division). I'll get some feedback from the other Perl 6 developers, and fix it if they agree. (Update: turns out that infix: is explicitly not coercive, but rather is specced to return a value of the same type as the arguments. Which won't work for generally for Str).
As Pat pointed out,
+$m
should also work, that's a long standing limitation in Rakudo.In general, coercion to a type is done with
$variable.Typename
, and I believe this works for all numeric types in Rakudo today.