我有以下格式的数据输出。 我从控制台上的命令获得此输出。
Number: 9
state: Online
Data: W1F-9YN
Device: 41
Number: 10
state: Online
Inquiry Data: W1-9YN
Device: 41
Number: 11
state: Online
Inquiry Data: W1-9YN
Device: N/A
Number: 42
state: Online
Data: WD-W WDZ-04J
但是,现在我想将其更改为以表格格式输出。 如下所示
Device number state data
41 10 online WY1-996
42 12 offline WY2-996
. . . .
. . . .
. . . .
我尝试使用下面给出的代码,但我无法以正确的格式排列,有时候所有数据都显示在一列中。谁能帮助我?
open WDLIST, "Command";
while (<WDLIST>) {
if (m/Device\s*:\s*(\d+)/) {
$enDevice = $1;
print "$enDevice";
}
if (m/Number\s*:\s*(\d+)/) {
$umber = $1;
print "$Number";
chomp;
}
if (m/state\s*:\s*(w+)/) {
$State = $1;
print"$State";
}
if (m/Data\s*:\s*(w+)(d+)(\-)(\s)/) {
$Data = $1;
print"$Data";
}
}
谢谢!
答案 0 :(得分:1)
您可以使用printf格式化输出。最简单的解决方案是用
替换所有打印语句printf "%-10s", $variable;
这将在10个字符宽的列中打印左对齐的变量。此外,您需要在每个数据块的开头或结尾打印换行符。
对于更完整的解决方案,我会将所有数据收集到一行的散列中,并在检测到数据块结束时将其打印出来:
printf "%-10s %-10s %-10s %-10s\n", $info{device}, $info{number}, $info{state}, $info{data};
(或使用哈希切片来减少冗长的代码)
基于每个Device
字段表示新设备启动的假设。我会改变你的代码工作:
open WDLIST, "Command";
my %device;
printf "%-10s %-10s %-10s %-10s\n", qw(Device number state data);
while (<WDLIST>) {
if (m/Device\s*:\s*(\d+)/) {
# Print previous device, if any.
printf "%-10s %-10s %-10s %-10s\n", @data{ qw(id number state data) }
if exists $device{id};
# Reset the current device and set the id
%device = ( id => $1 );
}
if (m/Number\s*:\s*(\d+)/) {
$device{number} = $1;
}
if (m/state\s*:\s*(w+)/) {
$device{state} = $1;
}
if (m/Data\s*:\s*(w+d+-\d+)/) {
$device{data} = $1;
}
}
# Print the last device (if any)
printf "%-10s %-10s %-10s %-10s\n", @data{ qw(id number state data) }
if exists $device{id};
(我有点不确定数据field
的最后一个正则表达式应该是什么。你的例子不一致。至少你需要解释你的示例输入的数据字段之间的关系并在您的示例输出中)