for ($#history .. 0) { my $temp = pop @history; if (!exists $history{ $temp }) { $history{ $temp }++; unshift @history; } # else nothing to do we've already removed it. }