2009-07-01 47 views
1

我想設置一個基本的錯誤檢查系統,它將捕獲由系統調用運行的shell錯誤。 execute_command是一個webmin函數,它運行系統調用,然後將錯誤消息設置爲其第四個參數。我基本上叫execute_command_error(「adduser的測試」),知道我已經創建,並根據我的預定義的陣列,用戶名爲test,ID指望它打印使用整數和字符串的多維數組

無法用戶
無法添加到 加該用戶,因爲它已經在系統上存在 。

而是我得到:

Uhhhhhhhhh?
Uhhhhhhhhh?

我已經驗證$ exe和$ return是「adduser」,並且是非常優秀的。 什麼是我不理解數組?它似乎忽略了字符串和或數字,然後按照3個元素的最後一個定義。什麼是解決方案或更好的解決方案?

以下是部份代碼:

$ErrorMsg['adduser',1,'title'] = "Unable to add user"; 
$ErrorMsg['adduser',1,'msg'] = "Unable to add that user because it already exists on the system."; 
$ErrorMsg['random',2,'duaisdhai'] = "Uhhhhhhhhh?"; 

sub execute_command_error 
{ 
    my $error = ""; 
    my $cmd = $_[0]; 

    $return = execute_command($cmd, undef, undef, \$error)>>8; 
    if ($error) { 
     my ($exe) = $cmd =~ m|^(.*?)[ ]|; 

     $exe_title = $ErrorMsg[$exe,$return,'title']; 
     $exe_msg = $ErrorMsg[$exe,$return,'msg']; 


     print $exe_title."<br>"; 
     print $exe_msg ."<br>"; 
    } 
} 

更新:

我想,我需要使用哈希值,我不知道爲什麼,我以爲我可以在指數使用字符串。有了這個說法,很少有研究讓我這樣:

%ErrorMsgs = ('adduser' => { 
       '1' => { 
        'title' => 'Unable to add user', 
        'msg' => 'Unable to add that user because it already exists on the system.', 
       }, 
      }, 
      ); 

現在我將如何使用變量引用它?因爲無論這些工作:

$exe_title = $ErrorMsgs{"$exe"}{"$return"}{"title"}; 
    $exe_title = $ErrorMsgs{$exe}{$return}{title}; 

回答

2

首先,看看perldsc爲做多維結構的正確語法。你的數組沒有任何意義。

如果您打開了warnings,您會看到「參數不是數字」警告,告訴您不能以任何有意義的方式在數組索引中使用字符串。

但是您在更新中發佈的散列應該可以正常工作。

#!/usr/bin/perl 

use strict; 
use warnings; 
## ^^ these things are your friends 

my %ErrorMsgs = ('adduser' => { 
         '1' => { 
           'title' =>  'Unable to add user', 
           'msg' =>  'Unable to add that user because it already exists on the system.', 
         }, 
       }, 
       ); 

my $exe = 'adduser'; 
my $return = 1; 

print $ErrorMsgs{$exe}{$return}{title}; # works 

如果你沒有得到你所期望的輸出,這是因爲有什麼毛病$exe$return - 他們可能不會在你試圖使用它們的範圍限定。打開strict,警告將有助於追蹤問題。

1

{'key'=>'val'}創建一個哈希引用,所以在查找一個鍵之前先解除引用。

$exe_title = $ErrorMsgs{$exe}->{$return}->{"title"}; 

您也不需要引用$ exe或$ return,因爲它們已經包含了字符串。

請注意,Perl不支持多維索引;一個多維數組只是一個數組數組,所以你需要爲每個索引使用[]。在標量上下文中,逗號運算符返回最右邊表達式的值,所以下面的兩行相當:

$ErrorMsg[0,1,2] = "foo"; 
$ErrorMsg[2] = "foo"; 

注意,在列表環境中,逗號運算符返回值的列表,這給了我們片:

@a=qw(f o o); 
@a[3,4,5] = qw(b a r); 
print join(',', @a), "\n"; 
# output: f,o,o,b,a,r 
@ErrMsg{qw(title msg)} = ('Unable to add user', 'Unable to add that user because it already exists on the system.')