my $prev = []; @array = grep { my $i = 0; my $ret = 0; $ret = 1 if $#$prev != $#$_; while ($ret && $i <= $#$prev and $i <= $#$_){ $ret = 1 if $prev->[$i] ne $_->[$i]; } $ret; } sort { my $i = 0; my $ret = 0; loop: while (1) { if ($i <= $#{$a} and $i <= $#{$b}){ # test if we still have something to compute $ret = $a->[$i] cmp $b->[$i]; # compute the difference of this element last loop if $ret; # if there's a difference return $i++; } else { # if the arrays are equal to this point in terms of elements, but not in length, we decide on the longer one $ret = $#{$a} <=> $#{$b}; # determine by length last loop; } } $ret; } @array;