2014-02-18 122 views
0

我希望有人能夠幫助我爲什麼我的while循環不會退出時,我附加兩個Android設備。Perl循環等待adb設備陣列

在SO研究的幫助下,我設法拼湊了下面的代碼,但是我添加了一個while循環來等待對Android'adb devices'命令的響應。我期待在此while while循環中等待兩個Android設備通過USB連接到我的PC,或者當兩個連接的設備打開時。我的代碼編譯好了,並且能夠在設備已經打開並連接時通過while循環工作,但是當我使用USB電纜將腳本啓動到android設備斷開連接時,然後幾秒鐘後插入USB連接在我的電腦中,腳本仍然在循環中。我在Windows 7上使用最新的Strawberry Perl運行此腳本。

任何指導都將不勝感激。

下面的代碼...

use strict; 
    use warnings qw(all); 

    use IPC::Run3; 
    use Carp qw(croak confess cluck); 
    use Data::Dumper; 

    my @devices = get_devices(); 
    my $devicesattached = ""; 

    while ([email protected]){ 
      get_devices(); 
      print "."; 
      sleep (1); 
      last if @devices; 
    } 

    print "\n\tDevice 1 is $devices[0]"; 
    print "\n\tDevice 2 is $devices[1]\n"; 

    sub get_devices { 
     my $adb_out; 
     run3 ["adb", "devices"], undef, \$adb_out, undef; 
     $? and cluck "Warning: non-zero exit status from adb ($?)"; 

     my @res = $adb_out =~ m/^([[:xdigit:]]+) \s+ device$/xmg; 
     return wantarray ? @res : \@res; 
    } 

非常感謝, MikG

+1

一旦你進入循環,你永遠不會改變'@ devices'。 – ThisSuitIsBlackNot

+0

@ThisSuitIsBlackNot:您的評論是正確的,應該寫爲答案。 – Borodin

+0

@Borodin工作。 – ThisSuitIsBlackNot

回答

3

你永遠不會改變@devices一旦進入循環。最簡單的解決方法是改變

while ([email protected]) { 
    get_devices(); 

while ([email protected]) { 
    @devices = get_devices(); 

但是,您可以進一步簡化代碼:

my @devices; 
until (@devices = get_devices()) { 
    print "."; 
    sleep 1; 
} 

注意,Perl有一個built-in debugger,可以幫助你在這樣的情況下這個。運行它:

perl -d /path/to/my/script 
+0

感謝您的反饋意見,我會在明天再次發表並回復您。雖然看過你的例子,現在看起來很明顯......仍在學習! – MikG

+0

謝謝ThisSuitIsBlackNot,它的工作原理!這正是我所期待的。 – MikG