Hi Sayth,

On Fri, 9 Dec 2011 03:35:02 -0800 (PST)
flebber <flebber.c...@gmail.com> wrote:

> 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

You don't need List::Util's sum() here as I shall demonstrate.

> 
> 
> 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";

You should add "$!" to the thrown exception.
> while (my $line = <$fh>) {
>     $sum += $line;
>     push (@num_array, $line);
> }

OK, so you're both keeping track of the sum, and also pushing the lines
themselves. One note is that you've forgotten chomp, and another is that you
can simply do:

my $count = 0;
my $sum = 0;

while (my $line = <$fh>) {
        chomp($line);
        $sum += $line;
        $count++;
}

And then divide $sum by $count. This will use O(1) of storage instead of O(N).

Regards,

        Shlomi Fish
> sub mean {

You need more empty lines when defining functions and they should be
consistently placed either before all the script's code or after it.

>         return sum(@_)/@_;}

The trailing "}" should be on its  own line.

> 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
> 
> 

Regards,

        Shlomi Fish

-- 
-----------------------------------------------------------------
Shlomi Fish       http://www.shlomifish.org/
My Public Domain Photos - http://www.flickr.com/photos/shlomif/

Confucius says: “XSLT made me realise humanity was hopeless.”.

Please reply to list if it's a mailing list post - http://shlom.in/reply .

--
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