Search code examples
perlloopssyntaxwhile-loopfactorial

perl - short factorial calculator returning long strings of 1's


I'm trying to make a program that calculates the factorial of a number. I'm not very familiar with perl, so I think I'm missing some grammar rule.

When I enter 5 the program should return 120. Instead it returns a few dozen 1's. When I try other numbers I still get 1's, but more or less of them depending on if I enter a higher or lower number.

Here's my code:

print"enter a positive # more than 0: \n";

$num = <STDIN>;
$fact = 1;

while($num>1)
(
    $fact = $fact x $num;
    $num = $num - 1;
)

print $fact;
system("pause");

This is my first post to stack Overflow, so I hope I obeyed all theposting rules.


Solution

  • The problem is this line:

    $fact = $fact x $num;
    

    x is not the multiplication operator in Perl. It is used to repeat things. 1 x 5 will produce "11111".

    Instead you want *.

    $fact = $fact * $num;
    

    Which can be written using *=.

    $fact *= $num;
    

    A few other issues...

    Get used to strict and warnings now. By default, Perl will let you use variables without declaring them. They are global, which is bad for reasons you'll learn later. Right now it means if you have a typo in a variable name like $face Perl won't tell you about it.

    Looping over a list of numbers is better done with a for loop over a range using ...

    # Loop from 1 to $num setting $factor each time.
    for my $factor (1..$num) {
        $fact *= $factor;
    }
    

    Instead of using a system call to pause the program, use sleep.