从文件中提取行时我遇到了奇怪的事情。
行来自在路由器上发送并保存到文件中的 SSH 命令。它们看起来像: 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
所以,在我的 PERL 脚本中,当我阅读这个文件时,我会这样做:
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);
输出应该是:
FastEthernet0 ; upup ; not set
FastEthernet1 ; upup ; not set
FastEthernet2 ; updown ; not set
但不幸的是,输出更像:
FastEthernet0 ; upup
; not set
FastEthernet1 ; upup
; not set
FastEthernet2 ; updown
; not set
我猜某处有一个换行符,可能在每个接口行的末尾。但我尝试了几件事,比如chomp($_)
,甚至
$_ =~ s/
//;
但事情变得更奇怪了。编辑:我尝试了其他答案,也有同样的问题。 使用鲍罗丁的回答:
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);
输出就像
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
我们越来越接近它,其他 FastEthernet 接口发生了什么?