The best approach would be to leverage the benefits of Lexical Scoping. ...a brief example...

for( 1 .. 100 ) { my @array; my $c = 0; while( $c++ < 500_000 ) { push @array, rand; } print "\@array holds ", scalar( @array ), " elements.\n"; }

On each iteration of the outer "foreach" loop, @array is declared, filled, checked for an element count, and then falls out of scope, at which time the memory is released back to Perl for the next iteration.

If you watch Perl's memory usage during the run of this script you will see that after the first iteration of the 'foreach' loop, Perl never requires any significant additional memory.

The other thing to consider is your algorithm itself. Do you need the entire file to be slurped into an array? Or can you iterate over it line by line and process each line individually? The latter will almost always be more memory efficient. And finally, even if you do slurp the entire file into an array, each time you slurp it again into the same array, the previous contents are discarded and that memory becomes available again to Perl. Nevertheless, careful use of lexical scoping solves a whole slew of potential problems, memory usage being only one of them.


Dave


In reply to Re: arrays : splice or undef ? by davido
in thread arrays : splice or undef ? by JockoHelios

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.