【问题标题】:How do I pass a complex number from the command-line to sub MAIN?如何将复数从命令行传递到子 MAIN?
【发布时间】:2016-03-08 15:59:57
【问题描述】:

我有以下简单的脚本:

#!/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 中有没有办法做到这一点?

【问题讨论】:

    标签: raku


    【解决方案1】:

    其实你写的很完美

    $ ./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 已经涵盖了其余部分。

    【讨论】:

      【解决方案2】:

      如果你在 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
      

      【讨论】:

      • 谢谢,效果很好。不幸的是,./square i 不起作用(没有为类 'Str' 的调用者找到方法'Complex'),你必须做./square 0+1i,但我可以忍受。
      猜你喜欢
      • 2019-07-27
      • 2023-04-02
      • 2020-10-09
      • 2012-07-26
      • 2018-09-02
      • 1970-01-01
      • 2021-08-30
      • 2012-02-04
      • 1970-01-01
      相关资源
      最近更新 更多