#!/usr/bin/perl
use strict;
use warnings;
# sample snmp return
my $mac_address = '0x001617479a5e';
print qq{Original MAC Address: $mac_address\n};
# reformat the address as a standard MAC
$mac_address =~ s/\A..//xms; # remove the 0x
$mac_address =~ s/(..)/$1:/g; # add a colon between bytes
$mac_address =~ s/:$//; # remove the trailing :
print qq{Reformatted MAC Address: $mac_address\n};
Refactorings
No refactoring yet !
mrxinu
July 21, 2008, July 21, 2008 00:33, permalink
This occurred to me as I was looking through some other code - unpack() and join().
#!/usr/bin/perl
use strict;
use warnings;
# sample snmp return
my $mac_address = '0x001617479a5e';
print qq{Original MAC Address: $mac_address\n};
# reformat the address as a standard MAC
$mac_address =~ s/^..//; # remove the 0x
$mac_address = join(':', unpack('A2' x 6, $mac_address)); # reformat with colons
print qq{Reformatted MAC Address: $mac_address\n};
Marco Valtas
July 21, 2008, July 21, 2008 05:59, permalink
I think there's a million ways to this, I think a simple call will keep the code smaller. The trick here is, first the 'g' flag turns the match operation a kind a loop, if put it in a while will work too. The join function catches all matches and glue with ':' and the group (?:0x) will take care on avoiding match the prefix '0x'.
Hope this helps.
#!/usr/bin/perl
use strict;
use warnings;
# sample snmp return
my $mac_address = '0x001617479a5e';
print qq{Original MAC Address: $mac_address\n};
$mac_address = join(':',($mac_address =~ m/(?:0x)?(\w{2})/g));
print qq{Reformatted MAC Address: $mac_address\n};
mrxinu
July 21, 2008, July 21, 2008 06:34, permalink
@Marco Brilliant! Thanks man. I don't think I'd used clustering much beyond making sure I wasn't causing needless backreference.
dionys.myopenid.com
September 11, 2008, September 11, 2008 09:23, permalink
$mac_address = join(':', ($mac_address =~ /(..)/g)[1 .. 6]);
Xavier Noria
October 7, 2008, October 07, 2008 12:39, permalink
Make octets apparent, and remove unneeded capture.
my @octets = substr($mac_address, 2) =~ /../g; $mac_address = join ':', @octets;
Seanbo
September 3, 2009, September 03, 2009 23:25, permalink
Why bother with the additional variable declaration for the individual octets?
my $reformatted = join ':', substr($mac_address, 2) =~ /../g;
Alex
November 15, 2010, November 15, 2010 07:43, permalink
Using CPAN, we have a module that takes care of the fiddly parsing of MAC addresses for us - though it doesn't handle SNMP style addresses just yet.
#!/usr/bin/env perl use strict; use warnings; use Net::MAC; my $mac_address = '0x001617479a5e'; $mac_address =~ s/^0x//; my $mac = Net::MAC->new( 'mac' => $mac_address ); my $reformatted = $mac->as_IEEE; print "Reformatted MAC address: $reformatted.\n";
Converting the return from an SNMP walk into a colon-delimited MAC address.