Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:


What does this error mean?



Use of uninitialized value in addition (+) at lib.pl line 13, <STDIN> line 1.





I've initialized my values so I'm not sure why the error...

Here is the full code (it is a library file):
#!/usr/bin/perl use strict; use warnings; my $line; sub calcsum { my @funcArray = @_; my $funcSum = 0; my $funcArr = 0; my $arrcount = scalar(@_); foreach my $line (@funcArray) { $funcSum += $line; } return ($funcSum); }
Here's the main file:
#!/usr/bin/perl use strict; use warnings; require 'lib.pl'; my @userArray = <STDIN>; my $sum = calcsum(my $funcSum); print "Sum $sum\n";

I'm still learning so please be kind. I've tried moving the "my $line;" after the sub line and it didn't make a difference.

Thanks.

Replies are listed 'Best First'.
Re: Use of uninitialized value in addition (+)
by vinoth.ree (Monsignor) on Apr 08, 2009 at 03:31 UTC

    You have declared the variable $funcSum but not assigned any value in it, So when you call the function  calcsum() with this argument it passes the undef value, So in function definition you are getting the error message

      Monks rule!
      Thanks
Re: Use of uninitialized value in addition (+)
by Anonymous Monk on Apr 08, 2009 at 03:10 UTC
    This
    ||||||||||||| VVVVVVVVVVVVV my $sum = calcsum(my $funcSum);<<<<< ^^^^^^^^^^^^^ |||||||||||||
    is equivalent to calcsum(undef);
      Monks rule!
      Thanks.
Re: Use of uninitialized value in addition (+)
by ELISHEVA (Prior) on Apr 08, 2009 at 04:05 UTC

    This one confused me a lot too when I was first learning Perl!

    You are probably thinking "yeah, sure - I *know* I passed an undefined variable to calcsum, but why is it causing a problem?! After all I passed "nothing" to calcsum!

    My guess is that you think you are passing an undefined "array" when actually you are passing a list with a single value undef in it: (undef). Thus your foreach loop is equivalent to:

    my @funcArray = (undef) #my @funcArray = @_; my $funcSum = 0; my $funcArr = 0; my $arrcount = 1; #my $arrcount = scalar(@_); foreach my $line ((undef)) { #foreach my $line (@funcArray) $funcSum += $line; }

    Who'd ever thought - so much confusion from nothing?

    Best, beth

Re: Use of uninitialized value in addition (+)
by toolic (Bishop) on Apr 08, 2009 at 17:18 UTC
    Since others have helped solve your problem, I thought I'd point out that the List::Util core module has a sum function equivalent to your calcsum function:
    use strict; use warnings; use List::Util qw(sum); my @userArray = <STDIN>; my $sum = sum(@userArray); print "Sum $sum\n";