Peter’s blog ✴ Week 185 ✴ 3 October 2022

THE WEEKLY CHALLENGE
Manipulating characters

The Perl Camel

Task 1

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.

Perl Weekly’s review

from PW issue 585

Another cool demo of regex in action. Task analysis is interesting too. Thanks for your contribution.

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';
}

9 lines of code

Output from script


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

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

 

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