David Ehresmann wrote:
List,

Hello,

I have a factorial script that calls a sub fact that does the
factorial and returns a value.  But I get this error when I execute
the script:

Use of uninitialized value in numeric gt (>) at fact.pl line 22.

Here is the script:

#!/usr/bin/perl

use warnings;
use strict;

fact();

You are calling the subroutine with no arguments so the contents of @_ are empty inside the subroutine and the variable is assigned undef instead of a valid value. From your subsequent post it looks like you want to declare the subroutine first which you would do like this:

sub fact;


my $num;

print "enter a number: \n";
chomp($num = <STDIN>);

my $x = fact($num);
print "the factorial is: $x\n";

sub fact {
        my $num = 0;
        $num = shift;

You probably want this instead:

        my $num = shift || 0;

That way you will always assign a valid number to the variable.


        my $res = 1;
        while ($num > 1) {
                $res *= $num;
                $num--;
        }

Another way to write that loop:

        for ( 1 .. $num ) {
                $res *= $_;
        }


        return $res;
}


John
--
Those people who think they know everything are a great
annoyance to those of us who do.        -- Isaac Asimov

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to