in reply to Re^2: Repeat question (redo)
in thread Repeat question

Do I need to store the random integers in variables or something.?

Yes, but you are already doing that. Here's one approach with a subroutine and using an array to hold the operands.

#!/usr/bin/env perl use strict; use warnings; while (1) { my @operands = (int(rand(100)), int(rand(100))); ask ($operands[0] > $operands[1], @operands); } sub ask { my ($subtract, @args) = @_; my $input; my $answer = $subtract ? $args[0] - $args[1] : $args[0] + $args[1] +; my $oper = $subtract ? '-' : '+'; until (defined $input && $input == $answer) { print "Nope, try again\n" if defined $input; print "What is $args[0] $oper $args[1] ? "; chomp( $input = <STDIN> ); }; print "Success!\n"; }

Edit: sigil fix on the ask() call.

Replies are listed 'Best First'.
Re^4: Repeat question (redo)
by hchana (Acolyte) on Nov 30, 2018 at 14:28 UTC

    wow.! this works great. Thank you. However, it appears rather complicated for me to understand and therefore learn from. Can I be cheeky and ask what the code is doing line per line.? No worries if you can't.

      Well, I don't want to over-explain since the best way to learn is often to figure things out for yourself. However, let's examine what I suppose could be the 2 most confusing parts.

      ask ($operands[0] > $operands[1], @operands);

      This is a subroutine call. You'll see we've defined the subroutine ask in the script? This is how it is called. There are either 2 or 3 arguments inside the brackets depending on how you see things. The first one is $operands[0] > $operands[1] which is a logical expression and therefore either true or false and the second one is @operands which is an array with the 2 random values previously assigned. Note that originally this line had an @ symbol at the start of $operands[0] which although OK was misleading (and a typo) so I've corrected it now.

      my $answer = $subtract ? $args[0] - $args[1] : $args[0] + $args[1];

      This is a variable assignment which computes the answer in one way or another depending on the logical value in $subtract which we passed into the sub as the first argument. It uses the ternary operator which is of the form condition ? eval-if-true : eval-if-false. Think of it as a short-hand way of writing an if-else block.

      The rest of the code is just loops and prints, really. See if you can trace through the logic now.

        Thank you very much. Appreciate your time.

        Hi again. I've been going through your code and it's starting to make sense. However, what is the function DEFINED going.?

        Until (defined $input && $input == $answer) { print "Sorry that's not right, please try again\n" if defined +$input;