Yes, it's simple. Yes, it's pathetic.

That's why I need help...!

This is essentially unedited; I decided I needed a standard deviation sub, so I wrote one. Then I remembered that I should get some of my code looked at for stylistic errors (and/or efficiency problems) and I figured, "Why not?" I stuck a little test of the sub on the end, and, here it is.

Be forewarned: This is probably bad code. This is most likely bad *design*. I'm using the shotgun theory here, which is essentially "code it and see what happens". I'm not good at any of this yet. You were warned.

#!c:\perl\bin\perl.exe -w use strict; use warnings; # This subroutine, given a set of values, should return the standard +deviation. sub standard_deviation { my $mean = 0; my $sample_size; my @differences; for (@_) { $mean = $mean + $_; } $sample_size = scalar(@_); $mean = $mean/$sample_size; for (@_) { @differences = (@differences, (($_-$mean)*($_-$mean))); } my $standard = 0; for (@differences) { $standard = $standard + $_; } $standard = sqrt($standard/$sample_size); return $standard; } my $stddev; my @values; @values = (22, 17, 29, 39, 20, 32); $stddev = standard_deviation(@values); print "The standard deviation is $stddev.";
Could this have been shorter? Should it have been longer? Is there some convention of math subs that's normally followed that I (forgot|don't know about)? Did I leave something out? Did I leave something in?

Anything at all, whatever it is, if it's not quite right or it just looks bad, please, let me know.

-----------------------
You are what you think.


In reply to Code Review! Go Ahead, Rip It Up! by chaoticset

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.