1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#!/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().
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#!/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.
refact
1 2 3 4 5 6 7 8 9 10 11 12
#!/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
1
$mac_address = join(':', ($mac_address =~ /(..)/g)[1 .. 6]);
Converting the return from an SNMP walk into a colon-delimited MAC address.