Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
PerlMonks  

Re: Finding sum of numbers and storing it an Array

by hippo (Bishop)
on Sep 21, 2020 at 09:20 UTC ( [id://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
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11121988]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others learning in the Monastery: (5)
As of 2024-03-28 14:17 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found