Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

Re: Finding average using package subroutine

by toolic (Bishop)
on Jul 14, 2011 at 00:09 UTC ( [id://914255]=note: print w/replies, xml ) Need Help??


in reply to Finding average using package subroutine

If you make the following changes, it should print "4":
package Average; # D e c l a r e a p a c k a g e # A v e r a ge a l i s t o f g r a d e s sub av { $total = 0; @grades = (3,4,5); $num_of_grades =$#grades + 1; foreach $grade ( @grades ) { $total += $grade; } $res = $total/$num_of_grades; # W h a t g e t s r e t u r n e d #print $res; return $res; } 1; #&av;

...and your script...

use warnings; use Average; $res = Average::av(); print $res;

You really meant to return a value ($res) from your sub. Eventually, you will probably also want to pass something as an argument to your sub. See also:

Replies are listed 'Best First'.
Re^2: Finding average using package subroutine
by boom.roasted (Initiate) on Aug 09, 2011 at 02:40 UTC
    I'm sort of teaching myself perl and have a similar problem. I used the problem above but I'm not getting the same results. I want to find the average using a <STDIN> and subroutines.

    here's what I've got:

    sub:

    sub avg {
    $n = 0;
    @array = (<STDIN>);


    $total =$#array + 1;

    foreach $array ( @array ) {
    $n += $array;
    }
    $res = $n/$total;
    return $res;
    }

    1;

    function:
    #!/usr/bin/perl

    require 'obj13-lib.pl';

    $res = avg();
    print $res;

    Where am I going wrong?

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://914255]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others pondering the Monastery: (4)
As of 2024-04-25 23:28 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found