Home > front end >  How to convert MAC Address formats in Perl?
How to convert MAC Address formats in Perl?

Time:07-06

I have to make a Perl script that gets a MAC address in the format HHHH.HHHH.HHHH where "H" is a hex digit, and give me a output of HH:HH:HH:HH:HH:HH. How can I make this conversion in Perl?

Here's an input text example:

System Information
Local port          :xgei-1/6/1
Group MAC address   :Nearest Bridge
Neighbor index      :1
Chassis type        :MAC address
Chassis ID          :4cf5.5b8b.f860
Port ID type        :Interface name
Port ID             :XGigabitEthernet0/0/1
Time to live        :109
Port description    :ZTE-2-C650-172.24.102.77
System name         :main-link-lab-cdi-sw-01

And here's my script's snippet where I treat the MAC Address data:

if ($linha =~m/^Chassis ID/){
            my($chassisID) = $linha=~ /:(.*)/g;
            $lldpInfo{$localInt}{"chassisID"} = $chassisID;
            print $chassisID."\n";  
}

In this case, I have to process the variable $chassisID.

Any suggestions?

Thanks!

CodePudding user response:

A quick and dirty approach could be to split the string on ., map the entries (assumed to be 4 characters each) into 2 character snippets separated by :, and then rejoin the results with : separators

my $chassisID = '4cf5.5b8b.f860';
# Transform the format:
$chassisID = join(':', map { substr($_, 0, 2).':'.substr($_, 2, 2) } split('\.', $chassisID));
print "ChassisID in MAC address format: $chassisID\n";

Output:

ChassisID in MAC address format: 4c:f5:5b:8b:f8:60

CodePudding user response:

You can use the NetAddr::MAC module from CPAN to parse and format MAC addresses in many different ways:

#!/usr/bin/env perl
use warnings;
use strict;
use feature qw/say/;
use NetAddr::MAC;

my $macaddr = '4cf5.5b8b.f860';
my $mac = NetAddr::MAC->new($macaddr);
say $mac->as_ieee; # 4c:f5:5b:8b:f8:60
  • Related