【发布时间】:2015-07-07 13:06:10
【问题描述】:
在我的last question 中,我询问了在我的 Perl 脚本中存储文本文件数据的正确方法,解决方案是使用 AoH。
反正我的实现好像不完整:
#!/usr/bin/perl
use strict;
use warnings;
# Open netstat output
my $netstat_dump = "tmp/netstat-output.txt";
open (my $fh, "<", $netstat_dump) or die "Could not open file '$netstat_dump': $!";
# Store data in an hash
my %hash;
while(<$fh>) {
chomp;
my ($Protocol, $RecvQ, $SendQ, $LocalAddress, $ForeignAddress, $State, $PID) = split(/\s+/);
# Exclude $RecvQ and $SendQ
$hash{$PID} = [$Protocol, $LocalAddress, $ForeignAddress, $State $PID];
}
close $fh;
print Dumper \%hash;
第一个问题是我在$PID 上得到未初始化的值错误,即使$PID 在上面的行中声明。
第二个脚本的问题是它从输入文件中加载最后一个字母并将它们放在自己的行中:
$VAR1 = {
...
'6907/thin' => [
'tcp',
'127.0.0.1:3001',
'0.0.0.0:*',
'LISTEN',
'6907/thin'
],
'' => [
'udp6',
':::49698',
':::*',
'31664/dhclient',
''
],
'r' => [
'udp6',
':::45016',
':::*',
'651/avahi-daemon:',
'r'
]
};
'' => 和 'r' => 来自输入文件,如下所示:
tcp 0 0 0.0.0.0:3790 0.0.0.0:* LISTEN 7550/nginx.conf
tcp 0 0 127.0.1.1:53 0.0.0.0:* LISTEN 1271/dnsmasq
tcp 0 0 127.0.0.1:631 0.0.0.0:* LISTEN 24202/cupsd
tcp 0 0 127.0.0.1:5432 0.0.0.0:* LISTEN 11222/postgres
tcp 0 0 127.0.0.1:3001 0.0.0.0:* LISTEN 6907/thin server (1
tcp 0 0 127.0.0.1:50505 0.0.0.0:* LISTEN 6874/prosvc
tcp 0 0 127.0.0.1:7337 0.0.0.0:* LISTEN 6823/postgres.bin
tcp6 0 0 ::1:631 :::* LISTEN 24202/cupsd
udp 0 0 0.0.0.0:46096 0.0.0.0:* 651/avahi-daemon: r
udp 0 0 0.0.0.0:5353 0.0.0.0:* 651/avahi-daemon: r
udp 0 0 127.0.1.1:53 0.0.0.0:* 1271/dnsmasq
udp 0 0 0.0.0.0:68 0.0.0.0:* 31664/dhclient
udp 0 0 0.0.0.0:631 0.0.0.0:* 912/cups-browsed
udp 0 0 0.0.0.0:37620 0.0.0.0:* 31664/dhclient
udp6 0 0 :::5353 :::* 651/avahi-daemon: r
udp6 0 0 :::45016 :::* 651/avahi-daemon: r
udp6 0 0 :::49698 :::* 31664/dhclient
这也让我觉得我的哈希函数没有解析整个文件并在某处中断。
【问题讨论】:
-
输入是否包含制表符或空格?
-
@choroba 是的,特别是在最后一列和它们之间(最后一行的列和空格之间的制表符)
-
@MagomedSegaIsmailov:制表符、空格或两者兼而有之?!
-
@choroba 我添加了输入,你可以在那里看到它,列之间的制表符和最后一列的空格。
-
@MagomedSegaIsmailov:您添加的输入中没有标签。
标签: arrays perl file hash while-loop