如何将复数从命令行传递到 sub MAIN?

How do I pass a complex number from the command-line to sub MAIN?

我有以下简单的脚本:

#!/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

其实你写的很完美

$ ./test.pl6 2+3i
2+3i squared is -5+12i

之所以会出现这个问题,是因为您实际上并没有在命令行中给它一个 Complex 数字。

$ ./test.pl6 2
Usage:
  ./test.p6 <x> 

您真正想要的是将其他 Numeric 类型强制转换为 Complex。所以你应该像下面这样写。

#!/usr/bin/env perl6

use v6.c;

sub MAIN ( Complex(Real) $x ) {
    say "$x squared is { $x*$x }";
}

我使用 Real 而不是 Numeric,因为 Complex 已经涵盖了其余部分。