There are two elements to my reply. One is to provide examples of a few techniques you may not have encountered yet (like using HEREDOCs in the print statements) and using if as a statement modifier (last if ...;).

The second element is to think about appropriate places to use a subroutine. Subs are generally used either to wrap up common code so it is only implemented once, or to wrap up some complex code so that it is easier to manage and understand. In either case using a sub makes code much easier to test because the sub can be tested in isolation.

Part of the Perl philosophy is TIMTOWTDI (there is more than one way to do it). However some ways are better than others and, especially while you are learning, it is good to see a variety of alternative solutions. In this case the original sample duplicated code by having two essentially identical subs, but didn't take advantage of a sub to wrap up the complicated task of getting and validating data from the user. Figuring out good places to use subs is quite an art and requires a fair degree of experience. Don't be afraid to change your mind about where and how to use subs in your code. Very often you can make code much easier to understand and maintain through refactoring (moving the code around) where subs play a very large part in how code is managed.

True laziness is hard work

In reply to Re^3: Subroutine Question by GrandFather
in thread Subroutine Question by Socrates440

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.