2
\$\begingroup\$

I have extensively consulted Raku documentation and have tried many combinations to finally arrive at this working solution.

#!/usr/bin/perl6
use v6;

my $a;
my $b = 34;
my $c;
$a = prompt "enter number: ";
$c = ($a * $b);
say  "$a multiplied by  $b is $c"; 
\$\endgroup\$
2
  • \$\begingroup\$ Hey there, welcome to the community! CodeReview.SE is to ask for peer reviews of code that is working as intended! For help with problems in your code, like the ones you seem to be exhibiting, you are better off asking at StackOverflow :) \$\endgroup\$ – RGS Apr 26 at 7:16
  • 1
    \$\begingroup\$ @AlexV The flawed code wasn't reviewed, so I threw it out and left the working code it. That should take care of it. \$\endgroup\$ – Mast Apr 27 at 20:47
3
\$\begingroup\$

To tighten your code a bit, you can declare my $a and assign in the same line:

my $a = prompt "enter number: ";
my $b = 34;
my $c;
$c = ($a * $b);
say  "$a multiplied by  $b is $c";

The above seems to solve your question, however a user might not respond with the proper input. If a user replies to the prompt with Hello you'll get an ungraceful error:

Cannot convert string to number: base-10 number must begin with valid digits or '.' in '⏏Hello' (indicated by ⏏) in block <unit> at Pedr_Ap_Glyn.p6 line 7

You can add a Type declaration to obviate this issue:

my Int $a = prompt "enter number: ";

...which, if an Int is not returned, will error with the message:

Type check failed in assignment to $a; expected Int but got [WHAT RAKU GOT IS HERE] in block <unit> at Pedr_Ap_Glyn.p6 line 5

Maybe a different pre-declared Type is more useful for your case:

my Numeric $a = prompt "enter number: ";

...which will work with non-Integer input (e.g. 3.14159265).

Or you could declare your own Type subset (below, "PosInt"):

subset PosInt of Int where * > 0;
my PosInt $a = prompt "enter number: ";

...which will only accept Ints greater that zero. Above are just a few options that the Raku language offers--and that you may wish to take advantage of.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.