I'm having weird things when extracting line from file.
Lines are coming from SSH commands sent on a router and saved into a file. They are looking like : saved_commands
FastEthernet0 is up, line protocol is up
Helper address is not set
FastEthernet1 is up, line protocol is up
Helper address is not set
FastEthernet2 is up, line protocol is down
Helper address is not set
So, in my PERL script, when i'm reading this file, I make this :
while (<LIRE>) {
$ifname = "";
$etat = "";
$myip = "";
if (/line protocol/) {
@status = split(/,/, $_) ;
@interface = split(/ /, $_);
$ifname = $interface[0];
for ($index = 0; $index <= $#status; $index++) {
@etat_par_if = split(/ /, $status[$index]);
$etat .= pop(@etat_par_if);
}
}
if (/Helper|helper/) {
@helper = split(/ /, $_) ;
$myip = pop(@helper);
if ($myip =~ /126/) {
}
else {
$myip = "not set";
}
}
if ($myip eq ""){
$myip = "not set";
}
if ($ifname ne ""){
print "$ifname ; $etat ; $myip \n";
}
}
close(LIRE);
The output should be :
FastEthernet0 ; upup ; not set
FastEthernet1 ; upup ; not set
FastEthernet2 ; updown ; not set
But unfortunately, the output is more like :
FastEthernet0 ; upup
; not set
FastEthernet1 ; upup
; not set
FastEthernet2 ; updown
; not set
I guess there's a newline somewhere, probably at the end of each interface line.
But i tried several things, like chomp($_)
, or even
$_ =~ s/
//;
But things get weirder. EDIT : I tried other answers, having same issue. Using Borodin's answer :
my ($etat, $ifname, $myip);
open(DATA,$fichier) || die ("Erreur d'ouverture de $fichier\n") ;
while (<DATA>) {
if (/line protocol/) {
$ifname = (split)[0];
my @status = split /,/;
for (@status) {
$etat .= (split)[-1];
}
}
elsif (/helper/i) {
my @helper = split;
$myip = (split)[-1];
$myip = 'not set' unless $myip =~ /\d/;
}
if ($ifname and $myip) {
print "$ifname ; $etat ; $myip\n";
$etat = $ifname = $myip = undef;
}
}
close(DATA);
The output is like
FastEthernet0 ; upup ; not set
Vlan1 ; downdowndowndowndowndownupupupdownupdownupdownupdownupdownupdownupdownupup ; 126.0.24.130
Loopback0 ; upup ; not set
Loopback1 ; upup ; not set
Tunnel100 ; upupupupupup ; not set
Dialer1 ; upup ; not set
Tunnel101 ; upup ; not set
Tunnel200 ; upup ; not set
Tunnel201 ; upup ; not set
Tunnel300 ; upup ; not set
We are getting closer to it, what happened to the others FastEthernet interfaces ?