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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With