Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
PerlMonks  

Finding average using package subroutine

by pinnacle (Acolyte)
on Jul 13, 2011 at 23:54 UTC ( [id://914254]=perlquestion: print w/replies, xml ) Need Help??

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

package

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; } #&av;

My perl script which calls above package

#!/usr/bin/perl use warnings; use Average; $d = Average::av($res); print $d;

When I run my script it gives me an error as stated below, I am missing some basic thing, please assist

Name "main::res" used only once: possible typo at ./ave.pl line 6. Use of uninitialized value $d in print at ./ave.pl line 7.

Replies are listed 'Best First'.
Re: Finding average using package subroutine
by toolic (Bishop) on Jul 14, 2011 at 00:09 UTC
    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:

      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: perlquestion [id://914254]
Approved by toolic
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (5)
As of 2024-04-19 23:44 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found