Robbie Hatley's Solutions, in Perl, for The Weekly Challenge #347 (“Format Date” and “Format Phone”)
For those not familiar with "The Weekly Challenge", it is a weekly programming puzzle with two parts, with a new pair of tasks each Monday. You can find it here: The Weekly Challenge
The Weekly Challenge for the week of 2025-11-10 through 2025-11-16 is #347. The tasks for challenge #347 are as follows:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Task 347-1: Format Date
Submitted by: Mohammad Sajid Anwar
You are given a date in the form: 10th Nov 2025. Write a script
to format the given date in the form: 2025-11-10 using the set
below:
@DAYS = ("1st", "2nd", "3rd", ....., "30th", "31st")
@MONTHS = ("Jan", "Feb", "Mar", ....., "Nov", "Dec")
@YEARS = (1900..2100)
Example #1:
Input: "1st Jan 2025"
Output: "2025-01-01"
Example #2:
Input: "22nd Feb 2025"
Output: "2025-02-22"
Example #3:
Input: "15th Apr 2025"
Output: "2025-04-15"
Example #4:
Input: "23rd Oct 2025"
Output: "2025-10-23"
Example #5:
Input: "31st Dec 2025"
Output: "2025-12-31"
To solve this problem, I use a "month map" hash to map month names back to numbers.
Robbie Hatley's Perl Solution to The Weekly Challenge 347-1
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Task 347-2: Format Phone Number Submitted by: Mohammad Sajid Anwar You are given a phone number as a string. Write a script to format the given phone number using these rules: 1. Remove all non-digit characters. 2. Group digits into blocks of length 3 from left to right. 3. Handle the final digits (4 or fewer) specially: - 0 digits: zero blocks - 1 digits: one block of length 1 - 2 digits: one block of length 2 - 3 digits: one block of length 3 - 4 digits: two blocks of length 2 4. Join all blocks with dashes. Example #1: Input: "1-23-45-6" Output: "123-456" Example #2: Input: "1234" Output: "12-34" Example #3: Input: "12 345-6789" Output: "123-456-789" Example #4: Input: "123 4567" Output: "123-45-67" Example #5: Input: "123 456-78" Output: "123-456-78" Example #6: Input: "42" Output: "42" Example #7: Input: "" Output: ""
To solve this problem, I'll use Perl's "substr" function to splice-off chunks of size 3 from the left while the size of the remainder is greater than 4, then handle the final 0-to-4 digits as described.
Robbie Hatley's Perl Solution to The Weekly Challenge 347-2
That's it for challenge 347; see you on challenge 348!
Comments
Post a Comment