We have a lot of code that uses Ethernet MAC addresses as identifiers. Sometime these are passed around nicely formatted as
aa:bb:cc:dd:ee:ff
where the letter pairs represent hexadecimally-encoded octets. Sometimes however a script will be passed a Cisco-style address:
0001.0203.0405
or even worse, something copied and pasted from a Windows dialog box:
00-01-02-03-04-05
The one-liner below converts incoming MAC addresses in (almost) any format into the desirable form, with octets separated by colons. The MAC to be filtered is in $_.

This could of course be cleaned up, using a qr// to avoid duplicating the hex-octet identifier.

s/([0-9a-f]{2})[^0-9a-f]*/$1:/ig;chop;

Replies are listed 'Best First'.
Re: MAC Pretty-printer
by thor (Priest) on Jan 21, 2005 at 04:37 UTC
    Whenever I see chop, wonder if something is wrong. Not saying that it's wrong to use it here, but just saying. What about this code?
    s/[[:^xdigit:]]//g; $mac = lc join ":", unpack "(A2)*", $_

    thor

    Feel the white light, the light within
    Be your own disciple, fan the sparks of will
    For all of us waiting, your kingdom will come

      In this case, I'm chopping the character added by the regexp, so I'm pretty sure it's safe. While your code is cleaner, my original is leaner - I went for brevity over clarity, since it sees a lot of use as a one-liner in passing MACs to non-perlish scripts (yes, I know, we have some of those.. I'm sorry ;) ).