perl logo Perl logo (Thanks to Olaf Alders)

The weekly challenge 347 - Task 2: Format Phone Number

 1 #!/usr/bin/env perl
 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-347/#TASK2
 3 #
 4 # Task 2: Format Phone Number
 5 # ===========================
 6 #
 7 # You are given a phone number as a string containing digits, space and dash only.
 8 #
 9 # Write a script to format the given phone number using the below rules:
10 #
11 ## 1. Removing all spaces and dashes
12 ## 2. Grouping digits into blocks of length 3 from left to right
13 ## 3. Handling the final digits (4 or fewer) specially:
14 ##    - 2 digits: one block of length 2
15 ##    - 3 digits: one block of length 3
16 ##    - 4 digits: two blocks of length 2
17 ## 4. Joining all blocks with dashes
18 #
19 ## Example 1
20 ##
21 ## Input: $phone = "1-23-45-6"
22 ## Output: "123-456"
23 ##
24 ##
25 ## Example 2
26 ##
27 ## Input: $phone = "1234"
28 ## Output: "12-34"
29 ##
30 ##
31 ## Example 3
32 ##
33 ## Input: $phone = "12 345-6789"
34 ## Output: "123-456-789"
35 ##
36 ##
37 ## Example 4
38 ##
39 ## Input: $phone = "123 4567"
40 ## Output: "123-45-67"
41 ##
42 ##
43 ## Example 5
44 ##
45 ## Input: $phone = "123 456-78"
46 ## Output: "123-456-78"
47 #
48 ############################################################
49 ##
50 ## discussion
51 ##
52 ############################################################
53 #
54 # First, we remove all whitespace and dashes. Then, we fill an
55 # array with the first three digits, keeping the remainder, unless
56 # there are 4 or less digits left, in which case we pick either two
57 # times two, or the remaining 3 or 2 digits.
58 
59 use v5.36;
60 
61 format_phone_numbers("1-23-45-6");
62 format_phone_numbers("1234");
63 format_phone_numbers("12 345-6789");
64 format_phone_numbers("123 4567");
65 format_phone_numbers("123 456-78");
66 
67 sub format_phone_numbers($phone) {
68     say "Input: '$phone'";
69     $phone =~ s/[\s-]*//g;
70     my @parts = ();
71     while(length($phone)) {
72         if(length($phone) > 4) {
73             push @parts, substr($phone, 0, 3, "");
74         } elsif (length($phone) == 4) {
75             push @parts, substr($phone, 0, 2, "");
76             push @parts, $phone;
77             $phone = "";
78         } else {
79             push @parts, $phone;
80             $phone = "";
81         }
82     }
83     say "Output: '" . join("-", @parts) . "'";
84 }