for ($#history .. 0) { my $temp = pop @history; next if exists $history{ $temp }; $history{ $temp } ++; unshift @history; }