A nice way of keeping things together when pre-allocating arrays is to use the fact that my is a function and do the declaration and preallocation in the same statement like this.

Update: I swear it worked 10 minutes ago when I tested it.But I tried it in a perl shell, and first time I tried it I did

$#{\@a} = 50; print scalar @a; which printed 51. Great!

Then I thought "Ah! Should have used my", so I recalled the line, and added the my, and again it printed 51.........so I posted.

My little perl shell has its uses, but ......

Thanks to sauoq who brought me to book.

$#{\my @array} = 100;

</Update>

The idea can also be extended to pre-allocating hash buckets like this

keys my %hash = 2**8;

Though this is tougher to verify as if you immediatly evaluate the hash in a scalar context print scalar %hash; you get 0, which is disconcerting. However, if you then add one key to the hash  %hash= (a=>1); print scalar %hash; you get 1/256 showing that it did work but simply fails to report the fact until it has at least one key.


Nah! Your thinking of Simon Templar, originally played by Roger Moore and later by Ian Ogilvy

In reply to Re: array pre-allocation trick by BrowserUk
in thread array pre-allocation trick 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.