in reply to Mean, Median and Mode
i used a bit of Frankenstein programming (a leg from vinoth.ree, an arm from the OP) to do what you probably want.
Each line from the file is split and then the length of the words are collected in @dataset. Afterwards the whole array of word lengths is used to build mean, median and std dev. So far no hash is needed, but you could of course use one to store the statistic properties in there.
The (untested) code is then like this:
#!/usr/bin/perl -w use strict; use warnings; sub mean { my (@data) = @_; my $sum; foreach (@data) { $sum += $_; } return ( $sum / @data ); } sub median { my (@data) = sort { $a <=> $b } @_; if ( scalar(@data) % 2 ) { return ( $data[ @data / 2 ] ); } else { my ( $upper, $lower ); $lower = $data[ @data / 2 ]; $upper = $data[ @data / 2 - 1 ]; return ( mean( $lower, $upper ) ); } } sub std_dev { my (@data) = @_; my ( $sq_dev_sum, $avg ) = ( 0, 0 ); $avg = mean(@data); foreach my $elem (@data) { $sq_dev_sum += ( $avg - $elem )**2; } return ( sqrt( $sq_dev_sum / ( @data - 1 ) ) ); } my $filename = "faketext.txt"; open my $fh, '<', $filename or die "Can't read from '$filename': $!\n" +; my @dataset; while(my $eachLine = <$fh>) { chomp($eachLine); push @dataset, map { length($_) } split( /[\s,]+/, $eachLine ); } print "Median: ", median(@dataset), "\n"; print "Mean: ", mean(@dataset), "\n"; print "Standard Dev.: ", std_dev(@dataset), "\n";
|
|---|