perl logo Perl logo (Thanks to Olaf Alders)

The weekly challenge 355 - Task 1: Thousand Separator

 1 #!/usr/bin/env perl
 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-355/#TASK1
 3 #
 4 # Task 1: Thousand Separator
 5 # ==========================
 6 #
 7 # You are given a positive integer, $int.
 8 #
 9 # Write a script to add thousand separator, , and return as string.
10 #
11 ## Example 1
12 ##
13 ## Input: $int = 123
14 ## Output: "123"
15 #
16 #
17 ## Example 2
18 ##
19 ## Input: $int = 1234
20 ## Output: "1,234"
21 #
22 #
23 ## Example 3
24 ##
25 ## Input: $int = 1000000
26 ## Output: "1,000,000"
27 #
28 #
29 ## Example 4
30 ##
31 ## Input: $int = 1
32 ## Output: "1"
33 #
34 #
35 ## Example 5
36 ##
37 ## Input: $int = 12345
38 ## Output: "12,345"
39 #
40 ############################################################
41 ##
42 ## discussion
43 ##
44 ############################################################
45 #
46 # As long as $int is more than 3 characters long, we prepend the
47 # last 3 digits of it and a "," to the current temporary result
48 # string. If there are 3 or less, just prepend those and the "," to
49 # the temporary result string. In the end, we have added one
50 # unnecessary "," at the very end, so we just remove that.
51 #
52 use v5.36;
53 
54 thousand_separator(123);
55 thousand_separator(1234);
56 thousand_separator(1000000);
57 thousand_separator(1);
58 thousand_separator(12345);
59 
60 sub thousand_separator($int) {
61     say "Input: $int";
62     my $out = "";
63     while(length($int) > 3) {
64         my $t = substr($int, -3, 3, "");
65         $out = "$t,$out";
66     }
67     $out = "$int,$out";
68     $out =~ s/,$//;
69     say "Output: $out";
70 }