in reply to move all 0s in an array to the beginning keeping other elements order same

G'day anilmwr,

Welcome to the monastery.

"Is there any better way to do this?"

That probably depends on what you mean by "better". Here's a different way of doing it which:

#!/usr/bin/env perl -l use strict; use warnings; my @array = (1, 2, 3, 4, 2, 1, 2, 0, 1, 0, 0); print "@array"; my $zeros = 0; @array = map { $_ == 0 ? ++$zeros && () : $_ } @array; unshift @array, (0) x $zeros; print "@array";

Output:

1 2 3 4 2 1 2 0 1 0 0 0 0 0 1 2 3 4 2 1 2 1

If by "better", you meant faster, use the builtin module, Benchmark, to find out.

-- Ken