具有split函数的Perl正则表达式

时间:2016-04-12 01:53:49

标签: perl perl-module

我编写了一个函数来解析在linux盒子上执行的命令的输出。我希望函数解析命令输出并将输出返回给调用函数。我想解析输出以获取0/9999 (0%)并返回0和9999.(注意:这些数字不是静态的。它可以是任意数量的数字。例如4567/100000 (45%))。我猜,我使用的正则表达式是不正确的。我将输出设为0。

命令输出:

Connecting to host 8.2.0.2, port 7775
[  4] local 9.1.1.2 port 37675 connected to 8.2.0.2 port 7775
[ ID] Interval           Transfer     Bandwidth       Total Datagrams
[  4]   0.00-2.40   sec  5.49 MBytes  19.2 Mbits/sec  10000
- - - - - - - - - - - - - - - - - - - - - - - - -
[ ID] Interval           Transfer     Bandwidth       Jitter    Lost/Total Datagrams
[  4]   0.00-2.40   sec  5.49 MBytes  19.2 Mbits/sec  5.958 ms  0/9999 (0%)
[  4] Sent 9999 datagrams

iperf Done.

功能:

sub test_output {

    my ($self) = @_;
    my $packets = 0;

    $self->{output_obj}->_exec('enter the command here');

    my @output = $self->{output_obj}->out();

    foreach my $line (@output) {
        if ($line =~ /(\d+\/\d+\s.*)/) {

            packets = $1
        }
    }
    my @values = split('/', $packets);
    foreach my $val (@values) {
        return "$val\n";
    }
}

函数调用:

$self->{'client'} = $self->{'exec_obj'}->test_output()

函数的预期返回值:

lost  : 0
total  : 9999
lost percentage: 0%

1 个答案:

答案 0 :(得分:0)

sub test_output {

    my $self = shift;

    $self->{output_obj}->_exec('enter the command here');

    my @output = $self->{output_obj}->out();

    foreach my $line (@output) {
        if ($line =~ m/(\d+)\/(\d+)\s\((\d+%)\)/) {
            my ($lost, $total, $percentage) = ($1, $2, $3);

            return ($lost, $total, $percentage);
        }
    }
}

my ($lost, $total, $percentage) = $self->{'exec_obj'}->test_output()