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
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |