【发布时间】:2014-07-31 09:08:13
【问题描述】:
从文件中提取行时我遇到了奇怪的事情。
行来自在路由器上发送并保存到文件中的 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 接口发生了什么?
【问题讨论】:
-
您在代码中的哪个位置执行
chomp($_) -
我删除了它。我将进行编辑以向您展示 chomp 会发生什么
-
chomp 实际上做了什么
-
添加了 chomp 代码更改。好像界面消失了或者发生了一些奇怪的事情
-
use Data::Dumper; $Data::Dumper::Useqq = 1; print Dumper($_); print Dumper($/);。这将向您显示行尾的内容以及chomp将尝试删除的内容。