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.
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.