Previous

Next


35. Another Perl Example

  • A simple Perl script (and by no means the best example of fantastic Perl or regex programming, but hopefully it shows how to string everything we've covered so far together) to find the average traceroute time for each hop:
    
    #!/usr/bin/perl
    
    open(FILE, "/usr/sbin/traceroute -n $ARGV[0] 2>/dev/null|");
      while (<FILE>) {
        $data = $_;
        if ($data =~ m/^\s?\d+\s+(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\s+([0-9.]* ms|
    \*)\s+([0-9.]* ms|\*)\s+([0-9.]* ms|\*)/) {
          $ip = $1;
          $a = $2;
          $b = $3;
          $c = $4;
          $a =~ s/ ms//;
          $b =~ s/ ms//;
          $c =~ s/ ms//;
    
          $total = 0;
          $counter = 0;
          if ($a ne "*") {
            $total = $total + $a;
            $counter++;
          }
          if ($b ne "*") {
            $total = $total + $b;
            $counter++;
          }
          if ($c ne "*") {
            $total = $total + $c;
            $counter++;
          }
          $total = $total / $counter;
    
          print "$ip:    \t";
          printf("%7.3f", $total);
          print " ms\n";
        }
      }
    close(FILE);
            
          

Previous

Next

Andrew Hill

For LinuxSA Meeting, 21 November 2000