Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

[Homework Question] Subroutines & References

by Hayest (Acolyte)
on Feb 11, 2015 at 16:00 UTC ( [id://1116344]=perlquestion: print w/replies, xml ) Need Help??

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

Hello, I'm looking to complete a homework assignment I've got: "Create and test a PERL program that uses a subroutine to take a list of numbers and return the ones that are above the average (mean). Hint: consider creating another subroutine to calculate the mean. From the calling program, display the results." I've got something along so far, but it won't execute:

#!/usr/bin/perl use strict; use warnings; use List::Util qw(sum); my @list_of_numbers = (1 .. 50); my $i = (); my $a = (); sub mean { return sum(@_)/@_; } sub above_mean { $i == mean(@list_of_numbers); foreach (@list_of_numbers) { if ($a > $i) { print "$a is above mean, which is mean(@list_of_numbers)"; } print above_mean(@list_of_numbers);
The error I get is as follows:
Missing right curly or square bracket at main.pl line 21, at end of li +ne + + syntax error at main.pl line 21, at EOF + + + Execution of main.pl aborted due to compilation errors.

I feel like I might be missing something stupid but I've been working on this for a while and can't make it work. Does anyone have any suggestions? Thanks!!!

Replies are listed 'Best First'.
Re: [Homework Question] Subroutines & References
by BrowserUk (Patriarch) on Feb 11, 2015 at 16:07 UTC

    sub above_mean { $i == mean(@list_of_numbers); foreach (@list_of_numbers) { if ($a > $i) { print "$a is above mean, which is mean(@list_of_numbers)" +; } #........^ this is missing } #...^ so is this }

    With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority". I'm with torvalds on this
    In the absence of evidence, opinion is indistinguishable from prejudice. Agile (and TDD) debunked
      #!/usr/bin/perl use warnings; use List::Util qw(sum); my @list_of_numbers = (1 .. 50); my $i = (); my $a = (); sub mean { return sum(@_)/@_; } sub above_mean { $i == mean(@list_of_numbers); foreach (@list_of_numbers) { if ($a > $i) { print "$a is above mean, which is mean(@list_of_numbers)"; } } } print above_mean(@list_of_numbers);

      This now returns:

      Use of uninitialized value $a in numeric gt (>) at main.pl line 16.

      However, I thought I declared $a earlier in my program?

        == is the numeric comparison operator, not the assignment operator, which is quite similar: =. See perlop for details. warnings should have told you:
        Useless use of numeric eq (==) in void context at ...

        Also, you don't populate $a anywhere. Maybe, you meant

        foreach my $a (@list_of_numbers) {
        لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ
        print above_mean(@list_of_numbers);

        Just as a matter of curiosity, you might try this variation on the quoted statement:
            print above_mean();
        Does calling the  above_mean() function without any parameters make any difference to the value returned by the function? If not, why not?


        Give a man a fish:  <%-(-(-(-<

Re: [Homework Question] Subroutines & References
by MidLifeXis (Monsignor) on Feb 11, 2015 at 17:11 UTC

    ++ for tagging it as homework, providing code, errors, etc.

    You have been given some advice already, let me add my $0.02.

    • @_ contains the parameters to a sub. See (original) lines 11 for use, and line 14/15 for lack of use.
    • Declare variables as close to use as possible (usually). Line 16 => foreach my $a (@list_of_numbers) {. See also your use of $i on line 15. Declare it right there.
    • Your requirements state that you want to return the list of numbers. Are you sure you want to print on line 18? Perhaps grep would help. As an example, to return a set of numbers that are between 4 and 8, you could do something like grep { $_ > 4 && $_ < 8 } @numbers. This could probably be used to replace you entire foreach loop. Conversely, look at push to store the results within your foreach loop.
    • Line 15 does not do what you think it does. You are using ==, a comparison operator, when you want =, an assignment operator.
    • Instead of the call on line 18 to mean(@list_of_numbers) (which does not do what you think it does within the string), why not just use $i, which you have already calculated.
    • I would probably choose different variable names. $a => $number, $i => $mean, @list_of_numbers => @numbers. The '@' sigil indicates an array, so 'list_of_' is redundant. $i needs me to look back to its assignment to remember what it actually holds. $a is not as far, but it has the same problem. Anything that can be done to keep the person from having to backtrack when reading your code makes it easier to read.
    • Kudos on using List::Util for calculating the sum. Easy enough to do by hand, but since that isn't the purpose of the exercise, there is no sense cluttering up the assignment with support code.

    --MidLifeXis

Re: [Homework Question] Subroutines & References
by toolic (Bishop) on Feb 11, 2015 at 16:24 UTC
    perltidy can help make this type of error more obvious by auto-indenting your code:
    #!/usr/bin/perl use strict; use warnings; use List::Util qw(sum); my @list_of_numbers = ( 1 .. 50 ); my $i = (); my $a = (); sub mean { return sum(@_) / @_; } sub above_mean { $i == mean(@list_of_numbers); foreach (@list_of_numbers) { if ( $a > $i ) { print "$a is above mean, which is mean(@list_of_numbers)"; } print above_mean(@list_of_numbers);
      Thanks for the suggestion, I could use that (big time). It still doesn't execute with the correct bracket location, however. Looking into it now... I'm a complete beginner with programming, and Perl. This community has been nothing but helpful to me. Thanks again!

        "Correct bracket location" doesn't enter into it.

        The hint is that your final print statement is deeply indented after tidying. It is indented to the same level as the if statement, because that's where it goes based on the brackets you wrote.

        You didn't want it to be at the same level as the if statement, and that's the clue that you need to add the close brackets.

Re: [Homework Question] Subroutines & References
by grasshopper!!! (Beadle) on Feb 12, 2015 at 01:05 UTC

    This might help

    #!/usr/bin/perl -w sub above_mean { my @array=@_; my $sum=0; foreach $i (@array) { $sum+= $i; } my $mean = $sum/ @array; return grep { $_ > $mean} @array; } my @a=1..100; foreach my $i (above_mean(@a)) { print "$i\n"; }

      And how does this help the OP?

      In case you hadn't noticed, this is a homework question. Giving the OP a working solution (that they likely won't understand) isn't the aim here - helping the OP develop their own working solution (whilst learning the skills required to do so) is the entire point of the exercise.

        Thank you for your concern, however, I was able to come up with my own solution before this was posted. In any means, this post was another example of how I could reach my end goal, but i was able to forge my own path to get there. Thanks again!
      foreach $i (@array) { ... }

      Posted code won't run under strictures due to non-declaration of  $i iterator. Making  $i lexical fixes this:
          foreach my $i (@array) { ... }
      (Running with  use strict; and  use warnings; is highly recommended for beginning Perl programmers — and for non-beginners as well!)


      Give a man a fish:  <%-(-(-(-<

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://1116344]
Approved by toolic
Front-paged by blindluke
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others meditating upon the Monastery: (5)
As of 2024-04-19 12:37 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found