我正在尝试解析 traceroute 字符串并获取服务器延迟。我已经设法做到了,但输出包括延迟和“ms”。我如何摆脱“ms”,是否可以平均三个延迟?

#!/usr/bin/perl
use strict;
use warnings;

my $str = " 1  sgp-1.valve.net (103.28.54.1)  1.030 ms  1.040 ms  1.212 ms";
my ($a, $b, $delaya, $delayb, $delayc) = split /  /, $str;

print "$delaya\n";
print "$delayb\n";
print "$delayc\n";

返回:
1.030 ms
1.040 ms
1.212 ms

预期的:
1.030
1.040
1.212

最佳答案

您可以使用正则表达式而不是拆分来执行此操作:

my $str = " 1  sgp-1.valve.net (103.28.54.1)  1.030 ms  1.040 ms  1.212 ms";
my ($delaya, $delayb, $delayc) =
    ($str =~ /([0-9.]+)\s+ms\s+([0-9.]+)\s+ms\s+([0-9.]+)\s+ms/);
print join "\n", $delaya, $delayb, $delayc, "\n";

产量:
1.030
1.040
1.212

正则表达式分割(以下表达式重复 3 次):
(               # beginning of a capturing group
    [0-9.]+         # a sequence of numbers and dot (at least one character)
)               # end of a capturing group
\s+             # at least one space
ms              # string 'ms'

如果你想要平均值,那么:
my $str = " 1  sgp-1.valve.net (103.28.54.1)  1.030 ms  1.040 ms  1.212 ms";
my @delays = ($str =~ /([0-9.]+)\s+ms\s+([0-9.]+)\s+ms\s+([0-9.]+)\s+ms/);
my $total;
$total += $_ for @delays;
my $avg = $total/@delays;
print $avg, "\n";

产量:
1.094

关于regex - 解析字符串并在perl中执行操作,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58794406/

10-17 03:12