Hmmm... once I puzzled my way through your unusual indentation, I noticed a few things that would make this better code.
- You don't declare any of your variables. Get into the habit of doing that by always using the strict pragma. Also turn on warnings, since that will frequently catch the $self->bonk() type problems that would otherwise leave you scratching your head for a while.
- This code: if (grep(/$engine/,@{$HoL_engine{$router}}) != 1)
screams "hash!" to me. You're trying to keep track of which "engines" appear in each "router", right? Hashes do all the work of checking for existing values for you, like this:$HoH_engine{$router}{$engine} = 1; instead of
if (grep(/$engine/,@{$HoL_engine{$router}}) != 1){
push @{$HoL_engine{$router}}, $engine;
}
Avoiding grep has the handy side effect of skirting the problem of 0 being false, which cLive points out above. Alternatively, you could use an array if you knew the values would all be small integers, like this: $HoL_engine{$router}[$engine] = 1;. That would require that you get the list out at the end with $engine{$router} = join(",", grep {$_} @{$HoL_engine[$router]});. Notice that this won't have the same truth problems as your initial form.
- It looks like you're reading from the dirhandle <DIA> instead of the filehandle <DIAFILE> that you just opened. I'd be surprised if your code would work at all with that, so I'm guessing that's a typo.
After all that, we're left without something like this, which worked for me on manufactured data.
use strict;
use warnings;
my %router_of_interest = ( router1 => 1, router2 => 1 );
# ....
my %engine;
opendir DIA, '/';
while (my $file = readdir(DIA)) {
next unless $file =~ /(.*)\.bbnplanet.net/;
my $router = $1;
next unless exists $router_of_interest{$router};
my %HoH_engine;
open(DIAFILE, "<$file") or die "Cannot open $file: $!\n";
while (my $line = <DIAFILE>) {
chomp $line;
if ($line =~ /^\s*L3 Engine: (\d+)/i) {
my $engine = $1;
$HoH_engine{$router}{$engine} = 1;
}
}
if (exists $HoH_engine{$router}){
$engine{$router} = join(",", sort keys %{$HoH_engine{$router}});
}
else {
$engine{$router} = "NA"; #GSR IOS version too old
}
}
foreach my $key (sort keys %engine) {
print "$key - Engine $engine{$key}\n";
}
Update: Still broken? Odd... when I put L3 Engine: 0 - OC12 (622 Mbps) by itself in router1.bbnplanet.net, I get the outputrouter1 - Engine 0. Could something be wrong elsewhere?