It's an okay way to do it if you understand how it works. For future maintenance, it's better to have code that you understand than code you don't understand.

But if in the future, you ended up having 20 or 30 numbers instead of five, the code will become pretty nasty. You'll likely get random errors in your results, only to realize after hours of investigation that you included $num17/$totalSum in the array, but forgot to include +$num17 when adding the numbers together. Or something like that.

For that reason, I'd recommend using an array to keep your numbers in.

#!/usr/bin/env perl use strict; use warnings; my @nums = ( 5, 10, 15, 20, 25 ); # Loop through the array to add each number, one at a time to make the + total. my $totalSum = 0; for my $num ( @nums ) { $totalSum += $num; } # Map loops through a list, applying a block to each item, to create a + new list my @array = map { $_ / $totalSum } @nums; print "The required numbers are: @array";

Because adding a list of numbers together is a pretty common thing to do, there's a function called sum that comes with Perl to do it:

#!/usr/bin/env perl use strict; use warnings; use List::Util 'sum'; my @nums = ( 5, 10, 15, 20, 25 ); my $totalSum = sum @nums; my @array = map { $_ / $totalSum } @nums; print "The required numbers are: @array";

You probably don't need to worry about whether the user will have List::Util installed. It has been bundled with Perl since 2002.


In reply to Re: Finding sum of numbers and storing it an Array by tobyink
in thread Finding sum of numbers and storing it an Array by shabird

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.