#2. In the check() function, if a hit is found, I would like the item move to the top of the list (representing it should stay in the cache longer). What I need to do is remove the current item ($_ as it stands now) and tack it on to the end of the list via a push. How would you recommend doing it? I dont care about cleverness, or obsfucation, but raw number of instructions. I had though of doing an undef $_; inside the loop, but that doesn't seem to actually remove the item from the array, just undef it out (the list continues to have the same # of elements). I suspect I need to splice it, but without having the index of the element of the array, I couldn't figure out how to do it... efficiently.
You hit the nail on the head. Setting aside efficiency (I have a whole rant prepared for that) trying to splice up an array while iterating over it with for(LIST) is tough business. The easiest thing to do is to attack it with a for(init; test; increment) loop:
sub remove5s { my($aref)=@_; for(my $i=0; $i<@$aref; $i++) { $_=$$aref[$i]; unless ($_ % 5) { splice(@$aref, $i, 1); $i--; } } }
This sub removes elements that are evenly divisible by 5. Rather than splice them out, it could just as easily have pushed them onto the end of the list (but you didn't say which list) or swapped it with the element at the end (watch for terminal conditions!).

In reply to Re: Efficiency Question by clintp
in thread Efficiency Question by mr.nick

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.