Perl6 / Rakudo : 변수의 데이터 유형을 어떻게 변경할 수 있습니까?
-
15-11-2019 - |
문제
#!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
. 해결책
You can always manually cast to Int
( $m.Int div $n.Int ).say;
Actually I would have hoped that prefix:<+> would work as in
( +$m div +$n ).say;
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.
다른 팁
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.