Try this. Note the comments in the code and see below for some references for further reading:
#!c:/perl/perl.exe
# ALWAYS use strict and warnings (see: strict, warnings)
use strict;
use warnings;
# In general, keep comments on separate lines from your code
# the first line in the world of perl.
print "My first Perl script\n\n";
# Declare the variables, and make them descriptive
my ($multiplier, $max_number);
# Get some input from the user
# Lets also validate it (we are only interested in "numbers")
# See perlre & perlretut
while (1) {
print "Please tell me the multiplication table required: ";
chomp($multiplier=<STDIN>);
# If it's a number, exit the loop
last if $multiplier =~ /^\d+$/;
}
# Same as above
while (1) {
# The following line wraps in a standard DOS window, so lets sprea
+d it
# over a couple of lines
print "Please tell me the multiplication Factor\n",
"(if you put more than 100, make sure you have a big screen!)
+ : ";
chomp($max_number=<STDIN>);
last if $max_number =~ /^\d+$/;
}
# Now, print out the table
# Use a "perlish" loop rather than a C-style one
# By doing it this way, we don't need the loop variable
# And we can instead just operate on $_
print "\nThe table is:\n\n";
for (1 .. $max_number) {
print "$_ X $multiplier = ", $_*$multiplier, "\n";
}
References: strict, warnings, chomp, perlre, perlretut, print
Cheers,
Darren :) | [reply] [d/l] |
use strict;
use warnings;
That should give you some interesting feedback to investigate when a script doesn't work ;-)
You could also use chomp on $num and $y to remove carriage returns etc. ie
chomp($num = <STDIN>);
I'm sure there are some more experienced monks who will contribute further.
Also check out some of the tutorials - they're very good.
(So is the O'reilly book - Learning Perl)
| [reply] [d/l] [select] |
$y=10;
for ($x=1;$x<=$y; $x++)
{
print "$x -->\t";
foreach (1..$y)
{
$result = $x*$_;
print "$result\t";
}
print "\n";
}
Change $y if required
Rds/Praveen | [reply] [d/l] |
You should get into the habit of using lexical variables instead of package variables, so:
$num = <STDIN>;
Would become:
my $num = <STDIN>;
While perl supports C style for loops it is usually preferred to use perl's for loops, so:
for ( $x = 1; $x <= $y; $x++ )
Would become:
for my $x ( 1 .. $y )
| [reply] [d/l] [select] |