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

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.

Replies are listed 'Best First'.
Re^5: Repeat question (redo)
by hippo (Archbishop) on Nov 30, 2018 at 15:18 UTC

    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;

        It returns true if its argument is defined and false otherwise. See perldoc -f defined.

        The first time through the loop, $input is undefined so we don't want to try to compare it with anything and we equally don't want to warn the user that their guess was wrong when they haven't even entered a guess yet.