If it makes sense to give a chunk of code a name that describes what the code does in a succinct fashion then the code should probably be in a sub.

If the same sequence of steps is performed in multiple places, they should be in a sub.

Breaking code up into subs does a few things for you. It:

  1. makes program flow clearer
  2. documents expected behavior
  3. makes testing easier
  4. reduces development time
  5. makes debugging easier

There is a rule of thumb that says "a sub should fix on a page (of whatever media you use)" which is a slightly useful guide in that anything much bigger than a page you probably can't understand easily as a unit, so should break up in to smaller pieces (subs). It's ok as a guide, but the more important driver is that it makes sense for the code in the sub to be treated as an entity. It's a little like breaking a web page into a number of nested pages where you don't have to follow all the links to make sense of the top page, but if you want the detail, follow the links.


Perl is environmentally friendly - it saves trees

In reply to Re: when to use subroutine by GrandFather
in thread when to use subroutine by convenientstore

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.