perl6 – 如何将复数从命令行传递到子MAIN?

前端之家收集整理的这篇文章主要介绍了perl6 – 如何将复数从命令行传递到子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到复杂的 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

猜你在找的Perl相关文章