【问题标题】:Why am I being warned about the use of an uninitialized value in the following Perl script?为什么会警告我在以下 Perl 脚本中使用了未初始化的值?
【发布时间】:2011-03-12 08:19:45
【问题描述】:

我正在尝试减少此列表中打印的端口数量:

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).

【问题讨论】:

  • 我们需要更多关于$hostz->tcp_ports('open')返回的信息。
  • if ($port ~~ (qw(80 445 515 9100)) { ... } 怎么样?

标签: perl xml-parsing


【解决方案1】:

很可能,表达式$hostz->tcp_ports('open') 返回了undef,而不是您预期的数字。

【讨论】:

  • 我在 if ($port != undef) { 现在它在 parse-nmap-xml.pl 第 67 行显示 Use of uninitialized value in numeric ne (!=)。跨度>
  • 改用if (defined $port)
  • 感谢 Roman,没有更多未初始化的错误 :p 但现在我得到一个空列表!就像这样:A.B.C.D 0
  • 萨曼莎,现在这是一个不同的问题。请open a new question,并在那里发布更多代码以帮助调试; get_hosttcp_ports这两个方法很有意思,需要@ips_sorted/一些示例数据的内容。
【解决方案2】:

以下是如何从包含端口列表的字符串中选择感兴趣的端口:

#!/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"
}

【讨论】:

    【解决方案3】:

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

    你也可以在一行中完成:

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

    【讨论】:

      猜你喜欢
      • 2011-01-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多