(Abbreviations used: new for $new{$_}, and old likewise.)

My take on the way in your node:

Okay. grep is being called, which effectively loops over the entire array. For each element, new is being incremented, and old is being set to 1 if it doesn't exist already. If they are equal, or if new is one lesser, then 1 is returned, otherwise 0 is returned. old is set to new.

Now suppose we have this array: @array = qw(h e l l o w o r l d); Stepping through your algorithm:

$_ $new{$_} $old{$_} $ret ============================ h 1 1 1 e 1 1 1 l 1 1 1 l 2 1 0 o 1 1 1 w 1 1 1 o 2 1 0 r 1 1 1 l 3 2 0 d 1 1 1
which gives you h e l o w r d, which is then sorted. I see why it's working, because new+1 always !=old, and new==old only the first time an element is hit, so that sub-sub there tags only the first of each element for retrieval by grep. You don't need the second condition, and, granted, it's true that there are better ways to do it (see other replies for examples)... but this is how this one works, to the best of my knowledge.

You're right in saying that old will always be within 1 of new, but it will never be exactly 1 greater.

Hope this helps.

Update: Rrgh -- it happened again!


In reply to Re: quandery about a grep statement by premchai21
in thread quandery about a grep statement by jynx

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.