Perl question!
Apr. 13th, 2013 05:11 pmQuestion for people who are better at perl than I am (this is most people who program in perl):
So, I've got a script that gets MAC addresses and bridgeport/portdescription info from switches. And there's one subroutine that cleans up the MAC address that the switch gives out. I hand the function a MAC address that's in the form xx:xx:xx:xx:xx:xx, except the switch drops leading zeroes, so it might look like "0:ab:cd:b:ee:ef" instead of "00:ab:cd:0b:ee:ef". The subroutine breaks it up and turns the single digit segments ("a") into a two character segment ("0a") and returns the prettier MAC string. There's also a global variable "prettyMAC", and if that's set, it returns the MAC in xxxx.xxxx.xxxx format instead.
Here's the code:
It works, but I feel like there should be a more elegant way to do this in perl. Thoughts? Suggestions?
Thanks!
So, I've got a script that gets MAC addresses and bridgeport/portdescription info from switches. And there's one subroutine that cleans up the MAC address that the switch gives out. I hand the function a MAC address that's in the form xx:xx:xx:xx:xx:xx, except the switch drops leading zeroes, so it might look like "0:ab:cd:b:ee:ef" instead of "00:ab:cd:0b:ee:ef". The subroutine breaks it up and turns the single digit segments ("a") into a two character segment ("0a") and returns the prettier MAC string. There's also a global variable "prettyMAC", and if that's set, it returns the MAC in xxxx.xxxx.xxxx format instead.
Here's the code:
sub cleanMAC {
my ($mac) = @_;
my @explodedMAC = split(/:/,$mac);
if ($#explodedMAC == 5) {
my $i = 0;
while ($i < 6) {
if (length($explodedMAC[$i]) == 1) {
$explodedMAC[$i] = "0" . $explodedMAC[$i];
}
$i++;
}
} else {
print STDERR "Something is wrong - I have a MAC address I can't parse\n";
die "Borked MAC - aborting\n";
}
if ($prettyMAC) {
$mac = $explodedMAC[0] . $explodedMAC[1] . "." . $explodedMAC[2] . $explodedMAC[3] . "." . $explodedMAC[4] . $explodedMAC[5]
} else {
$mac = $explodedMAC[0] . ":" . $explodedMAC[1] . ":" . $explodedMAC[2] . ":" . $explodedMAC[3] . ":" . $explodedMAC[4] . ":" . $explodedMAC[5];
}
return ($mac);
}It works, but I feel like there should be a more elegant way to do this in perl. Thoughts? Suggestions?
Thanks!
no subject
Date: 2013-04-14 04:57 pm (UTC)