My script needs to get a series of numbers input by the user and find the average of them. I would like to use the line ‘end-of-file’ to show that the user is done inputting code. Any help would be appreciated. Below is what I have so far. I think I am really close, but I am missing something.
Code:
#! /usr/bin/perl
use 5.010;
print "Enter the scores and type end-of-file when done";
chomp(@scores = <STDIN>);
foreach (@scores) {
push_average(total(@scores));
}
sub total {
my $sum;
foreach (@_) {
$sum += $_;
}
sum;
}
sub average {
if (@_ == 0) {return}
my $count = @_;
my $sum = total(@_);
$sum/$count;
}
sub push_average {
my $average = average(@_);
my @list;
push @list, $average;
return @list;
}
You are quite close. Adding
use strict; use warningsat the top of every Perl script will alert you of errors that might go unnoticed otherwise.A few hints:
You forgot the sigil of
$sumin the last statement oftotal. Currently, you return a string “sum” (without strict vars), or possibly call a sub calledsum.You don’t need the
foreachin the main part, rather doThe
totalis already calculated insidepush_averageYou probably want to print out the resulting average:
The
push_averageis silly; you return a new array of one element. You could return that one element just as well.Suggested script: