我有以下琐碎的脚本:
#!/usr/bin/env perl6 use v6.c; sub MAIN($x) { say "$x squared is { $x*$x }"; }
当用实数调用它时,这种方法非常好,但我也希望将它传递给复数.
当我按原样尝试时,会发生以下情况:
% ./square i Cannot convert string to number: base-10 number must begin with valid digits or '.' in '⏏i' (indicated by ⏏) in sub MAIN at ./square line 7 in block <unit> at ./square line 5 Actually thrown at: in sub MAIN at ./square line 7 in block <unit> at ./square line 5
当我将脚本更改为
#!/usr/bin/env perl6 use v6.c; sub MAIN(Complex $x) { say "$x squared is { $x*$x }"; }
它完全停止工作:
% ./square i Usage: square <x> % ./square 1 Usage: square <x>
在目前的Perl 6中有没有办法做到这一点?
解决方法
如果你使用从Str到复杂的
Coercive type declaration,它会工作得更好:
sub MAIN(Complex(Str) $x) { say "$x squared is { $x*$x }"; }
然后:
% ./squared.pl 1 1+0i squared is 1+0i % ./squared.pl 1+2i 1+2i squared is -3+4i