开发者

Perl for loop iterates only once when calling a specific sub

I have this piece of code that reads the ouput of a traceroute for monitoring purposes.

This piece of code below works fine.

for ($i = 0; $i < $sizeloc; $i++) {
  for ($j = 0; $j < 1; $j++) {
    if ($j==0) {
      system("tracert " . $locations[$i][$j] . " > d:\\netmon开发者_如何学Python\\"
              . $locations[$i]      [$j+1] );
    }
  }
}

As soon as I call this sub read_outputfile($locations[$i][$j+1]); inside the loop, a problem occurs. It only iterates one object and then my program ends. So the first time it calls read_outputfile it runs the code in the sub. Only, it doesn't return to the loop. It just finishes.

for ($i = 0; $i < $sizeloc; $i++) {
  for ($j = 0; $j < 1; $j++) {
    if ($j==0) {
      system("tracert " . $locations[$i][$j] . " > d:\\netmon\\" .
             $locations[$i][$j+1] );
      read_outputfile($locations[$i][$j+1]);
    }
  }
}

sub read_outputfile{
  my( $location ) = @_;

  open ($location, "$location");
  while ($record = <$location>) {
    $i++;
    if ($i == 8) {
      $out = substr($record , 32);
      if($out != "88.15.160.255" ) {            
        mail($location);            
      }
    }
  }
  close($location);
}

Any input?


Always, and I mean always, start your Perl scripts with:

use strict;
use warnings;

If you add this, you will most likely immediately get error messages about undeclared variables. Fix those, for instance:

for (my $i = 0; $i < $sizeloc; $i++) {
    for (my $j = 0; $j < 1; $j++) {
        ...
    }
}

Once you've declared all your variables (in the right scope), your problem will almost certainly disappear.


It looks like read_outputfile will continue to increment $i until <$location> is exhausted, at which point it may be greater than $sizeloc so your outer loop will terminate.

As @bvr suggests, you could fix this by localising $i in read_outputfile with

sub read_outputfile{
  my $i;

  etc...
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜