my %seen; for (1 .. @history) { unshift @history, $seen{$history[-1]}++ ? $#history-- && () : pop @history; }