Camel
Peter
Peter Campbell Smith

Frequent funny formats

Weekly challenge 347 — 10 November 2025

Week 347: 10 Nov 2025

Task 2

Task — Format phone number

You are given a phone number as a string containing only digits, space and dashes.

  1. Removing all spaces and dashes
  2. Grouping digits into blocks of length 3 from left to right
  3. Handling the final digits (4 or fewer) specially:
    • 2 digits: one block of length 2
    • 3 digits: one block of length 3
    • 4 digits: two blocks of length 2
  4. Joining all blocks with dashes

Examples


Example 1
Input: $phone = '1-23-45-6'
Output: '123-456'

Example 2
Input: $phone = '1234'
Output: '12-34'

Example 3
Input: $phone = '12 345-6789'
Output: '123-456-789'

Example 4
Input: $phone = '123 4567'
Output: '123-45-67'

Example 5
Input: $phone = '123 456-78'
Output: '123-456-78'

Analysis

I wonder where this is the standard way of formatting phone numbers? For that matter, I wonder how many people now use phone numbers other than just as a string of digits?

But that's not what we're asked.

In my experience theses sorts of problems are most efficiently solved using substr and length, so that's what I did.

You could undoubtedly do it using a regular expression, but it's always messy using one when there's a decision that depends on the end of the string rather than the start.

Try it 

Try running the script with any input:



example: 3 14159 26535

Script


#!/usr/bin/perl

# Blog: http://ccgi.campbellsmiths.force9.co.uk/challenge

use v5.26;    # The Weekly Challenge - 2025-11-10
use utf8;     # Week 347 - task 2 - Format phone number
use warnings; # Peter Campbell Smith
binmode STDOUT, ':utf8';
use Encode;

format_phone_number('1-23-45-6');
format_phone_number('1234');
format_phone_number('12 345-6789');
format_phone_number('123 4567');
format_phone_number('123 456-78');
format_phone_number('02072221212');

sub format_phone_number {
    
    my ($phone, $output, $length);
    
    # initialise
    $phone = shift;
    say qq[\nInput:  '$phone'];
    $phone =~ s|[^[0-9]||g;
    
    # groups of 3
    while (length($phone) > 4) {
        $output .= substr($phone, 0, 3) . '-';
        $phone = substr($phone, 3);
    }
    
    # and the rest
    $output .= length($phone) == 4 
        ? substr($phone, 0, 2) . '-' . substr($phone, 2, 2) 
        : $phone;
    
    say qq[Output: '$output'];
}

Output


Input:  '1-23-45-6'
Output: '123-456'

Input:  '1234'
Output: '12-34'

Input:  '12 345-6789'
Output: '123-456-789'

Input:  '123 4567'
Output: '123-45-67'

Input:  '123 456-78'
Output: '123-456-78'

Input:  '02072221212'
Output: '020-722-212-12'

 

Any content of this website which has been created by Peter Campbell Smith is in the public domain