【发布时间】:2016-04-30 00:01:17
【问题描述】:
当我在一行上打印 2 个变量时,第二个变量会覆盖第一个变量。我怀疑其中一个字符串中有“隐藏”字符,如此处所述concatenateing string variables overwrites them
如何“正确”打印?我怎样才能让 Perl 准确地告诉我分配给变量的字符串中的每个字符?如果不是“隐藏”字符,那有什么问题?
代码是...
#!/usr/bin/perl
use strict;
use warnings;
print "\n\nstart\n\n";
open CFG, "sw.cfg"
or die "Unable to open file sw.cfg: $!";
my $a;
my $b;
my $c;
while (<CFG>) {
if (/interface/) {
$a = substr ($_, 10);
}
if (/description/) {
$b = substr ($_, 12);
chomp ($a);
chomp ($b);
# $c = join ("--", $a, $b);
print "$a,\n";
# print "$c\n"
}
}
来自文件句柄的一些输入数据
interface FastEthernet0/1
spanning-tree portfast
!
interface FastEthernet0/2
spanning-tree portfast
!
interface FastEthernet0/3
description AP STM
spanning-tree portfast
!
interface FastEthernet0/4
description PORTAGE
spanning-tree portfast
enter code here
我的脚本实际输出的内容...
start
,astEthernet0/3
,astEthernet0/4
,astEthernet0/5
,astEthernet0/7
,astEthernet0/9
,astEthernet0/11
我认为它应该在打印“FastEthernet 0/3”之后加上逗号
这解决了问题...
while (<CFG>) {
**s/\r\n\z//;**
if (/interface/) {
【问题讨论】:
-
请提供一些示例输入数据,以及您希望看到的输出。没有看到数据,我们不知道
interface和description是否在同一行。这是一个可能的问题,因为您可能从错误的位置打印。 -
接口 FastEthernet0/1 生成树端口快!接口 FastEthernet0/2 生成树端口快!接口 FastEthernet0/3 描述 AP STM 生成树端口快!接口 FastEthernet0/4 描述 PORTAGE 生成树端口快速
-
另外,在当前代码中您不打印 2 个变量,您只打印 "$a,\n";
-
是文件的一行,或者多行。更新您的问题,粘贴 5 行左右,并确保它们正确分开,以便我们知道我们正在处理什么。我怀疑
$a, $b, $c在每次迭代/行上都会被覆盖 -
我最初试图打印 $a,一些空格,然后是 $b。当这不起作用时,我决定在值之后用逗号打印 $a 。我试图将这两个变量加入一个新的字符串,同样的问题。