in reply to Braino - why is this not working?
You must know that in 'grep', the special variable '$_' refers to each current item in @res, which hides the reference to item in @{$ar}.
the first time in loop, @res is empty, so $ans is 0, and the first item in @{$ar} is pushed in @res.
the 2nd time, @res contains that first item, grep select every item that equals itself. there's 1 item , and it equals itself, so $ans is 1, no push.
the 3rd time,@res still contains 1 item, still no push
...
@res always contains the that first item.