Your situation is a perfect example of why you should never type anything more than once for a specific amount: If you're doing it a few times now, you'll be doing it more in the future.

In this case, you just happened to be able to fill up the array with ten ones. Later on, you had to change that to 100. As a programmer, you should count on that happening and plan accordingly.

What's more, the actual number of items in the list needs to be made clear. If I'm trying to read your code, and I'm wondering how many ones there are, I have to count. That's not fun. Never mind you having to type 100 ones: What about the next person to read your code (who could be you) having to count those 100 ones.

Why are there 100 ones? I don't know, and your code doesn't tell me. Is it the number of wangos that you're processing? Then comment it:

my @arr = (1) x 10; # We can process 10 wangos.
Better yet, define a variable that tells how many wangos you can process:
my $max_wangos = 10; my @arr = (1) x $max_wangos;
Best of all, define a constant that is easily changeable AND describes what you're doing:
use strict MAX_WANGOS => 10; my @arr = (1) x MAX_WANGOS;
An excellent book that these concepts, and many many more, is Steve McConnell's excellent Code Complete. No serious programmer should be without it.

xoxo,
Andy
--
<megaphone> Throw down the gun and tiara and come out of the float! </megaphone>


In reply to The defensive programming way to fill an array by petdance
in thread Filling an array by Anonymous Monk

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.