Here is another version I quickly wrote as an example:
#!/usr/bin/perl use strict; use warnings; print "[Instructions as before, ctrl-c or \"quit\" to exit]\n"; OUTER: { my ($x, $y) = map { int rand $_ } qw/11 11/; INNER: { print "$x x $y = "; local $_ = <STDIN>; chomp; last OUTER if m/^quit$/; redo INNER unless m/^\d+$/; if ($_ == ($x*$y)) { print "Right!\n"; redo OUTER } else { print "Try again.\n"; redo INNER } } }
This is more to illustrate some features of Perl that are notably different from BASIC than to show "normal" Perl code, but I wrote it as a quick exercise.
First, you should always use strict and use warnings in almost any Perl program. These pragmas help to avoid common mistakes that previous versions of Perl silently allowed; thus the need for pragmas to avoid breaking backwards compatibility outright whilst tightening the language spec somewhat.
This version operates very similarly to yours. I didn't bother actually copying the instructions because they are of little value in teaching Perl.
The random numbers are assigned to variables $x and $y. Both variables are assigned as a list. This is one of the common ways to put function arguments into named variables, often seen as my ($x, $y) = @_. Here the same syntax assigns the list of two values map returns to $x and $y. The qw// is another syntax for a list literal, used here to provide arguments to map.
The reply from the user is stored in the default scratchpad variable $_ which is made local to the current dynamic scope. Because $_ is default for many operations, the chomp and the pattern match do not need to actually name the variable, although the same behavior does not apply to the subsequent test for numeric equality, where $_ must be explicitly named.
The regex test is actually necessary, since Perl considers strings that are empty or not parsable as numbers to be equal to zero.
Lastly, this program demonstrates two of Perl's loop control operators and their application to named blocks. Note the lack of explicit loops. Instead, the program repeatedly executes the OUTER and INNER blocks using the redo operator. If the user inputs "quit", the program exits the OUTER block using last. To be clear, this approach to iteration is not normal or recommended practice in Perl, but can occasionally produce more readable code and is out there.
In reply to Re: Basic Times Table excercise
by jcb
in thread Basic Times Table excercise
by jibberjabber
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |