为什么我在下面的Perl脚本中被警告使用未初始化的值?
问题描述:
我试图削减打印列表中的端口数:为什么我在下面的Perl脚本中被警告使用未初始化的值?
A.B.C.D 80,280,443,515,631,7627,9100,14000
到最有趣的,我的那些:
A.B.C.D 80,515,9100
为此,我使用这一位代码:
foreach (@ips_sorted) {
print "$_\t";
my $hostz = $np->get_host($_);
my $port = 0;
my $output = 0;
$port = $hostz->tcp_ports('open');
if ($port == 80 || $port == 445 || $port == 515 || $port == 9100) {
$output = join ',' ,$port;
}
print $output;
print "\n";
}
我可能不需要说,它不工作。我得到这个:
A.B.C.D 0
Use of uninitialized value $port in numeric eq (==) at parse-nmap-xml.pl line **(line with if).
答
这里是一个如何从包含端口列表的字符串中选择感兴趣的端口:
#!/usr/bin/perl
my %interesting = map { $_ => undef } qw(80 445 515 9100);
(undef, my $str) = split ' ', q{A.B.C.D 80,280,443,515,631,7627,9100,14000};
my @ports = grep { exists $interesting{$_} } split /,/, $str;
print "Interesting ports: [@ports]\n";
下面是我将重新编写代码:
#!/usr/bin/perl
my %interesting = map { $_ => undef } qw(80 445 515 9100);
for my $ip (@ips_sorted) {
print "$ip\t";
my $hostz = $np->get_host($ip);
unless (defined $hostz) {
warn "get_host returned undef for ip: '$ip'\n";
next;
}
my $port = $hostz->tcp_ports('open');
unless (defined $port) {
warn "tcp_ports returned undef for ip: '$ip'\n";
next;
}
(undef, my $str) = split ' ', $port;
my @ports = grep { exists $interesting{$_} } split /,/, $str;
if (@ports) {
print join(',', @ports);
}
print "\n"
}
答
$hostz->tcp_ports('open')
可能回报您应该存储在一个数组变量中的端口列表:@ports
而不是$ports
。然后你应该检查数组中的每个元素。
你可以做到这一点也只有一行:
$output = join(',', grep { $_ != 80 && $_ != 445 && $_ != 515 && $_ != 9100 } $hostz->tcp_ports('open'));
我们需要什么是'$ hostz-> tcp_ports返回更多的信息( '开放')'。 – dolmen 2010-07-06 15:21:33
if($ port ~~(qw(80 445 515 9100)){...}' – Ether 2010-07-07 02:44:13