2016-04-12 23 views
0

Bir linux kutusunda yürütülen komutun çıktısını ayrıştırmak için bir işlev yazdım. Fonksiyonun komut çıktısını ayrıştırmasını ve çıkışı arama işlevine döndürmesini istiyorum. Çıkışı 0/9999 (0%) almak ve 0 ve 9999'u döndürmek için ayrıştırmak istiyorum. (Not: bu sayılar statik değildir. Herhangi bir sayı olabilir. Örneğin 4567/100000 (45%)). Kullandığım normal ifade yanlış.Bölünmüş işlevle perl düzenli ifade

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. 

Fonksiyon:

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"; 
    } 
} 

Fonksiyon çağrısı: işlevinden

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

Beklenen dönüş değeri:

Ben 0.

Komut çıktısı olarak çıktı alıyorum

lost : 0 
total : 9999 
lost percentage: 0% 
+0

Burada birkaç probleminiz var. 1. "$ line" ile eşleşen RE, "0/9999 (% 0)" ile eşleşecek, böylece '/' üzerine bölündüğünüzde "0" ve "9999 (% 0)" olacaksınız. 2. Foreach döngüsünün içine bir dönüş koydunuz. İlk değeri döndürürsünüz, bu durumda "0" ... ve işte bu kadar. Ne döndürmeye çalıştığından emin değilim. Bir liste ise, neden sadece @values ​​döndürmüyor? –

+0

@MichaelAlbers 0, 9999 ve 0% ayrı ayrı dönmek istiyorum. – user3587025

+0

Perl'de bunu yapmamın tek yolu bir listeye dönmektir. Bir işlevden birden çok kez geri dönemezsiniz. Eğer şunu deneyerseniz: 'if ($ line = ~/(\ d +) \/(\ d +) [^ (] * \ ((\ d +%) \) /) {return ($ 1, $ 2, $ 3); (Bence, bunu test etmedim, ama bence doğru olması gerektiğini düşünüyorum.) –

cevap

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()