B5603dc8f1e87c251bf9b1d28f31d38f

Converting the return from an SNMP walk into a colon-delimited MAC address.

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 !

B5603dc8f1e87c251bf9b1d28f31d38f

mrxinu

July 21, 2008, July 21, 2008 00:33, permalink

No rating. Login to rate!

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

Marco Valtas

July 21, 2008, July 21, 2008 05:59, permalink

1 rating. Login to rate!

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

mrxinu

July 21, 2008, July 21, 2008 06:34, permalink

No rating. Login to rate!

@Marco Brilliant! Thanks man. I don't think I'd used clustering much beyond making sure I wasn't causing needless backreference.

Avatar

dionys.myopenid.com

September 11, 2008, September 11, 2008 09:23, permalink

No rating. Login to rate!
1
$mac_address = join(':', ($mac_address =~ /(..)/g)[1 .. 6]);

Your refactoring





Format Copy from initial code

or Cancel