The weekly challenge 347 - Task 1: Format Date
1 #!/usr/bin/env perl
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 use v5.36;
57
58 my @DAYS = get_days();
59 my @MONTHS = get_months();
60 my @YEARS = (1900..2100);
61
62 format_date("1st Jan 2025");
63 format_date("22nd Feb 2025");
64 format_date("15th Apr 2025");
65 format_date("23rd Oct 2025");
66 format_date("31st Dec 2025");
67
68 sub format_date($str) {
69 say "Input: '$str'";
70 my ($d, $m, $y) = split /\s+/, $str;
71 my $output = "${y}-" . indexed($m, @MONTHS) . "-" . indexed($d, @DAYS);
72 say "Output: '$output'";
73 }
74
75 sub indexed($str, @array) {
76 foreach my $i (0..$#array) {
77 if($str eq $array[$i]) {
78 return sprintf("%02d", $i+1);
79 }
80 }
81 return sprintf("%02d", 0);
82 }
83
84 sub get_days() {
85 my @DAYS = ("1st", "2nd", "3rd");
86 foreach(4..20) {
87 push @DAYS, "${_}th";
88 }
89 push @DAYS, "21st";
90 push @DAYS, "22nd";
91 push @DAYS, "23rd";
92 foreach(24..30) {
93 push @DAYS, "${_}th";
94 }
95 push @DAYS, "31st";
96 return @DAYS;
97 }
98
99 sub get_months() {
100 return ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
101 }
102