## Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people, just like you, are talking about what matters.

• Help others & share knowledge
• Earn cash & points
Solved

# perl calculations

Posted on 2009-07-06
198 Views
ok,

so I want to calculate the average value per line.

how do I write in code to add up the value of the variables, and divide that value by seven ?
0
Question by:MichaelGlancy

LVL 40

Accepted Solution

mrjoltcola earned 500 total points
ID: 24789880
my \$avg = (\$n1 + \$n2 + \$n3 + \$n4 + \$n5 + \$n6 + \$n7)/ 7;
0

Author Closing Comment

ID: 31600393
excellent. I didnt know there was an avg operator thing
0

LVL 84

Expert Comment

ID: 24789894
while( <> ){
next unless my @line=split/\D+/;
my \$sum=0;
\$sum+=\$_ for @line;
print "average=",\$sum/@line,"\n";
}
0

Author Comment

ID: 24789895
haha just realised there isnt, its another variable

see I know nothing
0

Author Comment

ID: 24789903
thanks ozo again

but it really does have to be stupid simple for me so I can follow it logically as best I can
0

LVL 84

Expert Comment

ID: 24789941
You didn't say that your variables were \$n1 + \$n2 + \$n3 + \$n4 + \$n5 + \$n6 + \$n7, so I added code to read variables into @line
0

LVL 48

Expert Comment

ID: 24790124
Here's another way that hopefully is very clear to read.
``````#!/usr/bin/perl
use List::Util 'sum';

open FILE, "file.csv" or die "Can not open file.csv \$!\n ;

while (<FILE>) {
my @line=split ',';
my \$avg = sum(@line) / @line;
print "avg=\$avg\n";
}
``````
0

## Featured Post

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

### Suggested Solutions

On Microsoft Windows, if  when you click or type the name of a .pl file, you get an error "is not recognized as an internal or external command, operable program or batch file", then this means you do not have the .pl file extension associated with …
I have been pestered over the years to produce and distribute regular data extracts, and often the request have explicitly requested the data be emailed as an Excel attachement; specifically Excel, as it appears: CSV files confuse (no Red or Green h…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
Six Sigma Control Plans