2011-04-03 21 views
0

我收到的時候我試圖運行我的第一個Perl腳本以下錯誤:[Perl的]:不是代碼引用......我的第一個劇本

[id=0 @ 0] : IP address "3.3.3.3" corresponds to device "core". 
Thread 1 terminated abnormally: Not a CODE reference at ./dev_ithread.pl line 23. 
[id=0 @ 1] : IP address "5.5.5.5" corresponds to device "border". 
Thread 2 terminated abnormally: Not a CODE reference at ./dev_ithread.pl line 23. 

這裏是我到目前爲止寫

#!/usr/bin/perl 

use strict ; 
use warnings ; 
use diagnostics ; 
use threads ; 
use Config ; 

$Config{useithreads} || die("\n---> Please recompile Perl with \<ithreads\> included. \n") ; 


# IP parameterization of network elements. 
my %device_ip = ( 
      "core" => "3.3.3.3", 
      "border" => "5.5.5.5",  
     ) ; 

# Initialize devices' pool of threads. 
my $index = 0 ; 
my @device_thread =() ; 
while(my ($key, $value) = each %device_ip)  
{ 
    push(@device_thread, threads->new(\&thread_job($key, $device_ip{$key}, $index))->join) ; $index = $index+1 ; 
} 

# Worker thread subroutine. 
sub thread_job 
{ 
    my ($device, $ip, $index) = @_ ; 

    my $ithread = threads->tid() ; 
    print "[id=$ithread @ $index] : IP address \"$ip\" corresponds to device \"$device\". \n" ; 
} 

我會很感激,如果有人能幫我解決這個問題。 謝謝。

回答

4

threads->new()的第一個參數必須是代碼引用或函數的名稱。您正在執行該函數並嘗試獲取結果的代碼引用(這很可能是真值,因爲這是print返回的值),因此是錯誤。我猜你的電話應該是這樣的:

threads->new(\&thread_job, $key, $device_ip{$key}, $index)->join 
+0

謝謝大家。有效! – user690182 2011-04-05 07:59:36

+0

@ user690182:太好了。您現在可以接受您認爲最能幫助您解決問題的答案之一。 – musiKk 2011-04-05 08:11:14

4

\&thread_job($key, $device_ip{$key}, $index)不會做你認爲它的作用:它會立即運行thread_job(...),然後生成其結果的參考。 threads->new然後嘗試在新線程內執行該引用,該引用不起作用,因爲它不是對sub的引用。

您可能想改爲說sub { thread_job($key, $device_ip{$key}, $index) }。 (或@ musiKk的版本。)

+0

我總是使用我的版本。但我很好奇:創建一個匿名子有什麼好處? – musiKk 2011-04-03 20:35:45

+0

@musiKk:對於快速的東西來說更方便,並且在通過代碼掃描時更容易閱讀,但如果你想使用某些變量作爲參數,它有時會表現怪異,這是由於Perl對封裝變量與閉包的交互方式有些奇怪的概念。 (詞法是由閉包捕獲的,但包變量將使用它們在閉包調用時的值,而不是創建時的值。)你的方法更可靠,更適合這些,並且在真正的程序中而不是快速測試這裏會是首選。 – geekosaur 2011-04-03 20:41:15

+0

好的,謝謝。 :) – musiKk 2011-04-03 21:21:58

相關問題