Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

raku

I've got the following trivial script:

#!/usr/bin/env perl6

use v6.c;

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

This works perfectly fine when calling it with real numbers, but I'd like to pass it complex numbers as well. When I try this as-is, the following happens:

% ./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

When I change my script to

#!/usr/bin/env perl6

use v6.c;

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

it stops working completely:

% ./square i
Usage:
  square <x>

% ./square 1
Usage:
  square <x>

Is there any way to do this in current Perl 6?

like image 882
mscha Avatar asked Dec 19 '22 19:12

mscha


1 Answers

Actually what you wrote works perfectly

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

The problem only shows up because you don't actually give it a Complex number on the command line.

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

What you really want is to coerce other Numeric types to Complex. So you should write something like the following.

#!/usr/bin/env perl6

use v6.c;

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

I used Real instead of Numeric, because Complex already has the rest of that covered.

like image 145
Brad Gilbert Avatar answered Jan 29 '23 19:01

Brad Gilbert