Pathologically Eclectic Rubbish Lister PerlMonks

### Statistic in Perl(Using Subroutines)

by stamp1982 (Novice)
 on Jul 10, 2013 at 22:19 UTC Need Help??
stamp1982 has asked for the wisdom of the Perl Monks concerning the following question:

Hello Monks

So I have three sets of data and I am trying to write a program that would calculate and print out for each of the data sets: number of measurements, average, variance and standard deviation (a subroutine should be used to do all). The program should also call the subroutines for each data set and print out the results.

So far this is what I have for the average. Please let me know where there are mistakes and how to proceed.
```use strict;
use warnings;
my @Dset1 = (5, 6, 7 , 8, 10);
my @Dset2= (10,11,12);
my @Dset3 = (16,48,49);

Data('Info',@Dset1);
Data('Info',@Dset2);
Data('Info',@Dset3);

my \$avg = average(\@data);
print "The average is \$avg \n";
sub average {
@_ == 1 or die ('Sub usage: \$average = average(\@array);');
my (\$array_ref) = @_;
my \$sum;
my \$count = scalar @\$array_ref;
foreach (@\$array_ref) { \$sum += \$_; }
return \$sum / \$count;
}

Replies are listed 'Best First'.
Re: Statistic in Perl(Using Subroutines)
by toolic (Bishop) on Jul 11, 2013 at 01:04 UTC
Re: Statistic in Perl(Using Subroutines)
by jwkrahn (Monsignor) on Jul 10, 2013 at 23:09 UTC
```sub average {
@_ == 1 or die ('Sub usage: \$average = average(\@array);');
my (\$array_ref) = @_;
my \$sum;
my \$count = scalar @\$array_ref;
foreach (@\$array_ref) { \$sum += \$_; }
return \$sum / \$count;
}
```sub average {
ref( my \$array_ref = \$_[ 0 ] ) eq 'ARRAY'
or die 'Sub usage: \$average = average(\@array);';
my \$sum;
\$sum += \$_ for @\$array_ref;
return \$sum / @\$array_ref;
}

Create A New User
Node Status?
node history
Node Type: perlquestion [id://1043577]
Approved by toolic
help
Chatterbox?
 [jdporter]: RonW - likely a reference to Matt Trout

How do I use this? | Other CB clients
Other Users?
Others musing on the Monastery: (8)
As of 2017-08-18 20:28 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
Who is your favorite scientist and why?

Results (310 votes). Check out past polls.

Notices?