On Sat, Dec 10, 2011 at 8:28 AM, Sayth Renshaw <flebber.c...@gmail.com>wrote:
> > > On Sat, Dec 10, 2011 at 7:44 AM, Rob Dixon <rob.di...@gmx.com> wrote: > >> On 09/12/2011 11:35, flebber 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 <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"; >>> >> >> With this program >> >> @data = <ARGV>; >> $sum += $_ for @data; >> print $sum / @data; >> >> in file 'average.pl' the command >> >> perl average.pl questions.txt > report.txt >> >> will do what you require :) >> >> >> Rob >> >> @shlomi >> > > Based on your feedback I have updated that script. > #!/usr/bin/perl > use warnings; > use strict; > > my $sum = 0; > my $filename = 'numbers3.txt'; > my $report = 'report.txt'; > open(my $fh, "<", $filename) or die "could not open $filename $! \n"; > my $count = 0; > > while (my $line = <$fh>) { > chomp($line); > $sum += $line; > $count++; > } > > open my $rh, ">", $report or die "Could not open file $! \n"; > print $rh "The total value is $sum \n"; > print $rh "The average is ", $sum/$count, "\n"; > > @Rob > > That does work well. I was concerned there would be no error message if > the file didn't exist, or if there were multiple files and one was missing. > But <ARGV> seems to create that error for us. > > C:\Documents and Settings\renshaw\My Documents>perl average.plnumbers.txt > numbe > rss.txt > report2.txt > Can't open numberss.txt: No such file or directory at average.pl line 4, > <> line > 6. > > C:\Documents and Settings\renshaw\My Documents> > > Thanks > > Sayth > > >