http://qs321.pair.com?node_id=266693

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

Yes, this is homework. I can add each number in an array just fine doing this:
for (@even){ $sum += $_; }
But can someone tell me why I can't multiply each element in an array with the folliwing (I'm getting the error message  Use of uninitialized value in multiplication (*)):
for (@odd){ $sum2 *= $_; }
Thanks,

Replies are listed 'Best First'.
Re: Adding and Multplying Elements in an Array
by dug (Chaplain) on Jun 18, 2003 at 01:28 UTC
    Since this is homework, I'll say this: Read the warning again. You were smart enough to ask them to talk to you, so you should listen to them.
Re: Adding and Multplying Elements in an Array
by djantzen (Priest) on Jun 18, 2003 at 01:43 UTC

    Using an undef variable in a mathematical operation causes its value to begin at zero. I don't see a formal explanation in perlop, but I would speculate that under warnings or -w you see the message regarding $sum2 being uninitialized because zero times anything is zero, and perl probably figures that you want to know in advance that you're performing a computation guaranteed to result in zero. Addition works because adding to zero isn't a problem. The solution therefore is to initialize $sum2 with a non-zero value.


    "The dead do not recognize context" -- Kai, Lexx
      I set  $sum2 = 1 and that seem to do it. Thanks.
        yes that's the way to tackle..... suresh
Re: Adding and Multplying Elements in an Array
by tcf22 (Priest) on Jun 18, 2003 at 01:34 UTC
    Since this is homework, I'm not gonna do it for you, but i'll give you a little hint. What value does $sum2 have before it enters the loop(or does it have a value). hmmm....
Re: Adding and Multplying Elements in an Array
by hmerrill (Friar) on Jun 18, 2003 at 13:40 UTC
    From all the reading I've done, and from all the advice I've been given, I make it a practice to *always* use warnings and strict, like this:
    #!/usr/bin/perl -w use strict;
    Doing that will save you some pain in that it won't allow you to do things like use variables before you declare them.

    Check out the perl style guide where "warnings" and "strict" are described, by doing
    perldoc perlstyle
    at a command prompt.

    HTH.
Re: Adding and Multplying Elements in an Array
by monsieur_champs (Curate) on Jun 18, 2003 at 14:58 UTC

    Hello, little fellow.

    Homework, hum? So I think you shall live by the Perl Motto "There Is More Than One Way To Do It tm". I use map to do it: map $sum+=$_, @even; and map $mul*=$_, ($sum=1),@odd;

    I'm posting this as a motivation for you try to figure "Yet Another Way To Do It tm". Please consider my proposal serioulsly.

    May the gods bless you.
    =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
    Just Another Perl Monk