Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

Re: Finding sum of numbers and storing it an Array

by hippo (Chancellor)
on Sep 21, 2020 at 09:20 UTC ( #11121988=note: print w/replies, xml ) Need Help??


in reply to Finding sum of numbers and storing it an Array

I have wrote a program that stores five numbers in different variables

This is the part which is confusing. You clearly know how to use arrays so why not start with an array?

my @nums = (5, 10, 15, 20, 25);

That way your sum could be written:

my $totalSum = 0; $totalSum += $_ for @nums;

or alternatively

use List::Util 'sum'; my $totalSum = sum @nums;

And your final array assignment could become

my @array = map { $_ / $totalSum } @nums;

By starting off with separate scalars, everything you do becomes repetitive. It's feasible for 5 numbers, but what about 30? or 100? or 1000000?

The other thing I would change is to remove the -w from the first line. Using warnings as you have done is better as it gives lexical scope and finer control where needed. The -w negates all that.


🦛

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://11121988]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others examining the Monastery: (4)
As of 2021-01-24 15:53 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Notices?