perl calculations


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 ?
Europa MacDonaldChief slayer of dragonsAsked:
Who is Participating?
mrjoltcolaConnect With a Mentor Commented:
my $avg = ($n1 + $n2 + $n3 + $n4 + $n5 + $n6 + $n7)/ 7;
Europa MacDonaldChief slayer of dragonsAuthor Commented:
excellent. I didnt know there was an avg operator thing
while( <> ){
  next unless my @line=split/\D+/;
  my $sum=0;
  $sum+=$_ for @line;
  print "average=",$sum/@line,"\n";
Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Europa MacDonaldChief slayer of dragonsAuthor Commented:
haha just realised there isnt, its another variable

see I know nothing
Europa MacDonaldChief slayer of dragonsAuthor Commented:
thanks ozo again

but it really does have to be stupid simple for me so I can follow it logically as best I can
You didn't say that your variables were $n1 + $n2 + $n3 + $n4 + $n5 + $n6 + $n7, so I added code to read variables into @line
Here's another way that hopefully is very clear to read.
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";

Open in new window

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.