Why am I being warned about the use of an uninitialized value in the following Perl script?
I am trying to cut down the number of ports printed in this list:
A.B.C.D 80,280,443,515,631,7627,9100,14000
to the ones that are most interesting for me:
A.B.C.D 80,515,9100
To do this, I am using this bit of code:
foreach (@ips_sorted) {
print "$_\t";
my $hostz = $np->get_host($_);
my $port = 0;
my $output = 0;
$port = $hostz->tcp_ports('开发者_JS百科open');
if ($port == 80 || $port == 445 || $port == 515 || $port == 9100) {
$output = join ',' ,$port;
}
print $output;
print "\n";
}
I probably don't need to say, that it's not working. I get this:
A.B.C.D 0
Use of uninitialized value $port in numeric eq (==) at parse-nmap-xml.pl line **(line with if).
Most likely, the expression $hostz->tcp_ports('open')
returned undef
, not a number like you expected.
Here is how one can select the interesting ports from a string containing the list of ports:
#!/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";
Here is how I would re-write your code:
#!/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')
probably returns a list of ports which you should store in an array variable: @ports
instead of $ports
. Then you should check each element of the array.
You can do it also in just one line:
$output = join(',', grep { $_ != 80 && $_ != 445 && $_ != 515 && $_ != 9100 } $hostz->tcp_ports('open'));
精彩评论