Reputation: 716
I have a perl script which runs on the cisco switch and executes 'show mac-address-table dynamic' command. It stores the data in a @ver. Then I have used regular expression to get the mac address only from @ver and then distinguish the mac addresses as per the required initial octet address. I now want the sorted as well unique mac address along with the counter as to how many times the unique addresses are repeated. I am using the linux command 'sort | uniq -d -c' for it. To explain it in short the script is as follows:
my @ver = $session->cmd('show mac-address-table dynamic');
my $mac_addr;
my @sonic_macaddr;
my @final_macaddr;
for my $line (@ver) {
if (my ($mac_addr) = $line =~ /((?:[0-9a-f]{4}\.){2}[0-9a-f]{4})/) {
$mac_addr = $1;
if ($mac_addr =~ m/^(0018)[.]/ or $mac_addr =~ m/^(a0ce)[.]/ or $mac_addr =~ m/^(0009)[.]/){
push (@sonic_macaddr, $mac_addr."\n");
@final_macaddr = qx (@sonic_macaddr | sort | uniq -d -c);
print @final_macaddr;
}
}
}
$session->close()
I am not getting the required output if I am using qx to execute it in the script itself otherwise it works fine on the command line. For example perl.pl | sort | uniq -d -c. Please suggest where I am going wrong. Thank you.
Upvotes: 0
Views: 108
Reputation: 829
If you have a list @list and you want the unique elements from it you have to use a hash :
my @list = ('c', 'c', 'a', 'a', '1', '1') ;
my %unic ;
for my $it (@list) {
$unic{$it}++
}
for my $k (sort keys %unic) {
print $k, " "
}
In your code I see a bunch of different issues, but it's difficult to propose a solution without the source file you're parsing.
@final_macaddr = qx (@sonic_macaddr | sort | uniq -d -c);
The perl idiom qx
("quote execute") forks out the execution to the OS, which does not know what @sonic_macaddr is, because it's a Perl variable ! Use a hash to "sort unic" within the Perl script.
push (@sonic_macaddr, $mac_addr."\n");
I wouldn't push the "\n" inside the list : you're much better adding it when printing ie :
for my $it (@sonic_macaddr) {
print $it, "\n" ;
}
Or even :
print join "\n", @sonic_macaddr ;
You never know when you'll need a clean list of mac addresses ;)
Upvotes: 3