为什么我在下面的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).

+0

我们需要什么是'$ hostz-> tcp_ports返回更多的信息( '开放')'。 – dolmen 2010-07-06 15:21:33

+0

if($ port ~~(qw(80 445 515 9100)){...}' – Ether 2010-07-07 02:44:13

这里是一个如何从包含端口列表的字符串中选择感兴趣的端口:

#!/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')返回undef,而不是一个数字,如你的预期。

+0

if if if if($ port!= undef){ 现在它说使用未初始化的值在数值ne(!=)at parse-nmap-xml.pl line 67. – Zenet 2010-07-06 14:32:55

+3

使用'if(defined $ port)'代替 – 2010-07-06 14:38:19

+0

感谢罗马,没有更多未初始化的错误:p 但现在我得到一个空list!就像这样: ABCD 0 – Zenet 2010-07-06 14:48:47

$hostz->tcp_ports('open')可能回报您应该存储在一个数组变量中的端口列表:@ports而不是$ports。然后你应该检查数组中的每个元素。

你可以做到这一点也只有一行:

$output = join(',', grep { $_ != 80 && $_ != 445 && $_ != 515 && $_ != 9100 } $hostz->tcp_ports('open'));