rmd: (fightclubanimated)
[personal profile] rmd
Question 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:
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!

Date: 2013-04-14 04:57 pm (UTC)
bryant: (Default)
From: [personal profile] bryant
Well, it's a concise solution in the spirit of line noise. I think [livejournal.com profile] frobzwiththingz is correct below.

Profile

rmd: (Default)
rmd

June 2025

S M T W T F S
1234567
89 1011121314
15161718192021
22232425262728
2930     

Most Popular Tags

Page Summary

Style Credit

Expand Cut Tags

No cut tags
Page generated Jan. 18th, 2026 05:47 pm
Powered by Dreamwidth Studios