Peter
Peter Campbell Smith

Manipulating characters

Weekly challenge 185 — 3 October 2022

Week 185 - 3 Oct 2022

Task 1

Task — Mac address

You are given MAC address in the form hhhh.hhhh.hhhh.

Write a script to convert the address to the form hh:hh:hh:hh:hh:hh.

Examples


Example 1
Input:  1ac2.34f0.b1c2
Output: 1a:c2:34:f0:b1:c2

Example 2
Input:  abc1.20f1.345a
Output: ab:c1:20:f1:34:5a

Analysis

I'm not great believer in one-liners as they are often hard to understand, but in this case I feel that:

say $test =~ m|^(..)(..).(..)(..).(..)(..)$| ? 
    qq[\nInput:  $test\nOutput: $1:$2:$3:$4:$5:$6] : 
	'Invalid format';

does the trick, including formatting the output as Mohammad specifies.

It could equally be done using substr() which we're told is faster, but it's hard to think of a real-life use case where it would make a difference.

Try it 

Try running the script with any input:



example: 1ac2.34f0.b1c2

Script


#!/usr/bin/perl

# Peter Campbell Smith - 2022-10-02
# PWC 185 task 1

use v5.28;
use utf8;
use warnings;

my (@tests, $test);

@tests = ('1ac2.34f0.b1c2', 'abc1.20f1.345a');

# just do it
for $test (@tests) {
    say $test =~ m|^(..)(..).(..)(..).(..)(..)$| ? 
        qq[\nInput:  $test\nOutput: $1:$2:$3:$4:$5:$6] : 
        'Invalid format';
}

Output


Input:  1ac2.34f0.b1c2
Output: 1a:c2:34:f0:b1:c2

Input:  abc1.20f1.345a
Output: ab:c1:20:f1:34:5a