The fact that arrays can grow to fit your needs is just one of the really great things with dynamic languages in general and with Perl in particular: no need to keep track of the size and to malloc new memory chunks.

Now, having said that, if you want to implement such a limitation, it is quite easy to do it: just don't access directly to your arrays, but do it through a small set of functions that check for bounds and return an exception when your program gets off-limits. So you could implement special versions of push, unshift to check bounds, as well as a set_val and a get_val mutator and accessor functions to access to the array elements.

Although I am not a great fan of OO programming in general, this is one case where it really makes sense and I might very probably implement it as an object-oriented module to create and manage arrays through a bunch of methods. (Or, perhaps, I would be tempted to do it with some closures, this usually makes it possible to do the thing in probably twice less code compared to OO code, but that's a different question and a matter of purely personal inclination.)

As mentioned by other monks before, a tied array might be a more transparent solution, but I haven't been really convinced so far by tied arrays and hashes.


In reply to Re: Array bounds checking by Laurent_R
in thread Array bounds checking by davehorsfall

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.