bluethundr has asked for the wisdom of the Perl Monks concerning the following question:

oh hai, monks.

I am re-trying my hand at perl and going through the Lllama one more time.

I'm attempting exercise 3 on chapter 4.

here's what I came up with:

-------------------

#!/usr/bin/perl -w use strict; sub avg { my $total; foreach (@_) { $total += $_; } print "This is the value of \$total: $total \n "; my $num = (@_); print "This is the value of \$num: $num \n"; return $total / $num; } sub above_avg { my $tot_avg = &avg(@_); print "This is the value of \$tot_avg $tot_avg \n"; my @product; foreach (@_) { if ($_ > $tot_avg) { (@product) = $_; } } print "This is the value of \@product @product \n"; return @product; } print "Please enter a series of numbers: "; my @entered = (<STDIN>); print "Here are the numbers above the average: ", &above_avg(@entered) +, "\n";
-----------------------------

The assignment is to produce a list of numbers that are above the average of a set of numbers input by the user.

For some reason, my array (@product) doesn't seem to be acting like an array. It only accepts ONE number instead of however many are above the average. Any hints?

Thanks!

Replies are listed 'Best First'.
Re: array does not accept more than one number
by ikegami (Patriarch) on Dec 09, 2008 at 23:55 UTC

    Assignments (as in "@product = ...;") replace the current contents of the variable to which data is being assigned. You need push here.

    As an extra exercise, you should replace "foreach (@_) { if ($_ > $tot_avg) { ... } }" with a call to grep.

    You should also look into separating I/O from computation. avg and above_avg shouldn't print anything.

    Why are you using "&" in front of subroutine calls? That tells Perl to ignore the subroutine's prototype. Do you have a reason to do that?

      Hi ikegami,

      I think your point about mixing computation & I/O may be a little unkind to the poster - methinx the OP contained the (admittedly primitive, but nonetheless effective) debug inserted whilst attempting to answer the question for themselves - shortly after which, they gave up and asked for help.

      That being said, ++ for the & hint - I didn't realise that - not that I use it anyway.

      A user level that continues to overstate my experience :-))
Re: array does not accept more than one number
by graff (Chancellor) on Dec 10, 2008 at 02:34 UTC
    ikegami is right (as usual). On top of what he said, some checking of values would be a good idea, to avoid unsightly crashes (like "divide by zero"). Suppose that you just fix the assignment to @product (using "push" as suggested in the first reply). Then run the script like this:
    $ your_script ^D
    (or "^Z", if you're using MS-windows/DOS-Prompt -- cmd.exe or command.exe -- instead of a linux/unix/macosx shell / bash for windows)

    What happens?

    My point is: check what $num is before you use it for division.