1 #!/usr/bin/perl
 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-197/#TASK1
 3 #
 4 # You are given a list of integers, @list.
 5 #
 6 # Write a script to move all zero, if exists, to the end while maintaining the relative order of non-zero elements.
 7 
 8 use strict;
 9 use warnings;
10 
11 # sample input values
12 my $inputs = [
13     [1, 0, 3, 0, 0, 5],
14     [1, 6, 4],
15     [0, 1, 0, 2, 0]
16 ];
17 
18 # handle all input arrays from sample list above
19 foreach my $input (@$inputs) {
20    print "(" . join(", ", @$input) . ") returns (" . join(", ", move_zero(@$input)) . ")\n";
21 }
22 
23 # given a list of integers, return the same list with all zeros moved to the end
24 sub move_zero {
25    my @values = @_;
26    my @return = ();
27    my @tmp = ();
28    # collect all non-zero values into @return, all zero values into @tmp
29    foreach my $elem (@values) {
30       if($elem == 0) {
31          push @tmp, $elem;
32       } else {
33          push @return, $elem;
34       }
35    }
36    # add all zero values to the end of @return before returning
37    push @return, @tmp;
38    return @return;
39 }