in reply to quandery about a grep statement

(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!