-
Notifications
You must be signed in to change notification settings - Fork 346
Expand file tree
/
Copy pathch-2.pl
More file actions
73 lines (48 loc) · 1.33 KB
/
ch-2.pl
File metadata and controls
73 lines (48 loc) · 1.33 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#!usr/bin/perl -w
# Created for perl weekly challenge - 180 - 2
# Write a script to trim the given list where element is less than or equal to the given integer.
# Must note that the given example is wrong.
use strict;
use warnings;
# sample calls
# my @sampleArray = (9,0,6,2,3,8,5);
# trimList(\@sampleArray, 4);
# my @sampleArray = (1,4,2,3,5);
# trimList(\@sampleArray, 3);
# my @sampleArray = (9,0,6,2,3,8,5);
# trimList_noPrint(\@sampleArray, 4);
# my @sampleArray = (1,4,2,3,5);
# trimList_noPrint(\@sampleArray, 3);
sub trimList
{
my ($arrayRef, $threshold) = @_;
my @output;
print( 'Output: (' );
for(my $i = 0, my $length = @$arrayRef; $i < $length; $i++)
{
my $elem = $arrayRef->[$i];
# check if the element is greater than the threshold
if($elem > $threshold)
{
push(@output, $elem);
print(",") if(@output != 1); #do not print a ',' before the first item
print($elem);
}
}
print( ')' );
return \@output;
}
# without print
sub trimList_noPrint
{
my ($arrayRef, $threshold) = @_;
my @output;
foreach my $elem (@$arrayRef)
{
if($elem > $threshold)
{
push(@output, $elem);
}
}
return \@output;
}