my @sparse = () ; while (...whatever...) { my $value = ... ; # next value my $col = ... ; # in this column my $row = ... ; # and this row if ($value) { # keep only the non-zeros push @sparse, [$col, $row, $value] ; } ; } ; @sparse = sort { ($$a[0] <=> $$b[0]) || ($$a[1] <=> $$b[1]) || die } @sparse ;