我有以下简单的脚本:

#!/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 到 Complex 的 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

10-07 14:59