(New to perl) I have a small perl program that calculates factorials. I'd like to use a while loop so that after the user gets a result, they will be asked "Calculate another factorial? Y/N" and have Y run the code again & have N end the program.
Here's my code:
print"Welcome! Would you like to calculate a factorial? Y/N\n";
$decision = <STDIN>;
while $decision == "Y";
{
print"Enter a positive # more than 0: \n";
$num = <STDIN>;
$fact = 1;
while($num>1)
{
$fact = $fact * $num;
$num $num - 1;
}
print $fact\n;
print"Calculate another factorial? Y/N\n";
$decision = <STDIN>;
}
system("pause");
What's giving me trouble is where to put the while loop and how to make the Y/N option work. I'm also unclear about system("pause")
and sleep
functions. I do know that system("pause")
makes my programs work though.
Your program is almost right, just a few issues:
use strict;
and use warnings;
to your scripts. They will
(beyond other things) force you to declare all the variables you use (with my $num=…;
)
and warn you about common errors (like typos). Some people consider it a bug that
use strict;
and use warnings;
aren't turned on by default.chomp
function.<
, >
, <=
, >=
, ==
, and !=
. For strings you must use
lt
(less-than), gt
, le
(less-or-equal), ge
, eq
, and ne
. If you use one of the number
operators on strings Perl will try to interpret your string as a number, so $decision == "Y"
would check whether $decision
is 0
. If you had use warnings;
Perl would have noticed you.
Use $decision eq "Y"
instead.while
loop had a trailing ;
just after the comparison which will give you an endless
loop or a no-op (depending on the content of $decision
). =
in $num = $num - 1;
."
around print "$fact\n";
system("pause")
only works on Windows where pause
is an external command. On Linux (where
I just tested) there is no such command and system("pause")
fails with command not found
.
I replaced it with sleep(5);
which simply waits 5 seconds..
#!/usr/bin/env perl
use strict;
use warnings;
print "Welcome! Would you like to calculate a factorial? Y/N\n";
my $decision = <STDIN>;
chomp($decision); # remove trailing "\n" from $decision
while ( $decision eq 'Y' ) {
print "Enter a positive # more than 0: \n";
my $num = <STDIN>;
chomp($num);
my $fact = 1;
while ( $num > 1 ) {
$fact = $fact * $num;
$num = $num - 1;
}
print "$fact\n";
print "Calculate another factorial? Y/N\n";
$decision = <STDIN>;
chomp($decision);
}
print "ok.\n";
sleep(5); # wait 5 seconds