Okay I have a working version for an answer to Gabor's exercises in
his udemy perl beginners training. But I think I am making it
unecessarily hard. Is there are clearer way to do this?

The scope of the question was? Given a Text file 'questions.txt'
filled with a single number each line. Create a report.txt that has
the average of the numbers printed out.

My solution is to add the numbers in the file to an array and then
find the average. I used a mean function I found on perlmonks. But how
can it be better?

#!/usr/bin/perl

use warnings;
use strict;
use List::Util qw(sum); # from http://www.perlmonks.org/?node_id=801356


my $sum = 0;
my $filename = 'numbers.txt';
my $report = 'report.txt';
my @num_array;
open(my $fh, "<", $filename) or die "could not open $filename \n";
while (my $line = <$fh>) {
    $sum += $line;
    push (@num_array, $line);
}
sub mean {
        return sum(@_)/@_;}
open my $rh, ">", $report or die "Could not open file \n";
my $answer = mean(@num_array);
my $title = 'Report by Sayth';
print $rh "The total value is $sum \n";
print $rh "The average is $answer \n";

Sayth


-- 
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to