使用整数和字符串的多维数组

时间:2009-07-01 07:50:46

标签: perl arrays multidimensional-array

我正在尝试设置一个基本的错误检查系统,它将捕获系统调用运行的shell错误。 execute_command 是一个webmin函数,它运行系统调用,然后将错误消息设置为其第4个参数。我基本上调用 execute_command_error (“adduser test”),知道我已经有一个名为test的用户创建并基于我预定义的数组,id期望它打印

  

无法添加用户无法使用   添加该用户,因为它已经   存在于系统中。

但我得到了:

  

Uhhhhhhhhh?
Uhhhhhhhhh?

我已经确认$ exe和$ return分别是“adduser”和1。 什么我不了解数组?它似乎忽略了字符串和/或数字,只是通过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 个答案:

答案 0 :(得分: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 :(得分:1)

{'key'=&gt; '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.')