gpt4 book ai didi

regex - 解析字符串并在perl中执行操作

转载 作者:行者123 更新时间:2023-12-01 23:16:00 25 4
gpt4 key购买 nike

我正在尝试解析 traceroute 字符串并获取服务器延迟。我已经设法做到了,但输出包括延迟和“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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com